`

Java 页面表格导出Word

    博客分类:
  • Java
阅读更多

StringBuffer sb = new StringBuffer();

//拼接字符串

sp = createStringBuffer();

 

//导出流到前台。

 InputStream is = new ByteArrayInputStream(sb.toString().getBytes());
  FileExport fe = new FileExport(String.valueOf(System.currentTimeMillis()), FileConstants.FILE_EXT_NAME_DOC);
  fe.exportFile(response, is);

 

 

 

 

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.idea.webframe.comm.log.LogWritter;


/**
 * Title: 系统组件 文件导出
 * Description: 中国税务税收征管信息系统
 * Copyright: Copyright (c) 2006
 * Company: 中国软件与技术服务股份有限公司
 * @author 康水明
 * @version 1.0
 */
public class FileExport {


    /**
     * 默认构造器
     * @param fileName文件名
     * @param contentTypeName 文件类型
     */
    public FileExport(String fileName, String contentTypeName) {
     initContentTypeMap();
        this.contentTypeName = contentTypeName;
        this.contentType = (String) contentTypeMap.get(contentTypeName);
        this.fileName = fileName;
    }

   
    /**
     * 私有构造器
     */
    private FileExport() {
    }
   
    //----------------------------公共接口----------------------------------------
   
    //对外提供的方法1  byte[]
    public void exportFile(HttpServletResponse response, byte[] bytes) throws IOException {
        if (!isZip && contentTypeName.equals(FileConstants.FILE_EXT_NAME_ZIP)) {
            LogWritter.sysDebug("执行doZippedExport(response, bytes, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doZippedExport(response, bytes, encodeType);
        } else {
            LogWritter.sysDebug("执行doExport(response, bytes, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doExport(response, bytes, encodeType);
        }
    }


    //对外提供的方法2  InputStream
    public void exportFile(HttpServletResponse response, InputStream in) throws IOException {
        if (!isZip && contentTypeName.equals(FileConstants.FILE_EXT_NAME_ZIP)) {
            LogWritter.sysDebug("执行doZippedExport(response, in, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doZippedExport(response, in, encodeType);
        } else {
            LogWritter.sysDebug("执行doExport(response, in, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doExport(response, in, encodeType);
        }
    }


    //对外提供的方法3   File      如果file是目录的话,需使用zip方式
    public void exportFile(HttpServletResponse response, File file) throws IOException {
        if (!isZip && contentTypeName.equals(FileConstants.FILE_EXT_NAME_ZIP)) {
            LogWritter.sysDebug("执行doZippedExport(response, file, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doZipExport(response, file, encodeType);
        } else {
            LogWritter.sysDebug("将file:" + file.getName() + " 转换成InputStream。。。。");
            FileInputStream in = new FileInputStream(file);
            LogWritter.sysDebug("执行doExport(response, in, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doExport(response, in, encodeType);
        }
    }


    //对外提供的方法4  List files   此种情况只支持输出为zip
    public void exportFile(HttpServletResponse response, List files) throws IOException {
        //先将头信息设置为zip类型的
        this.contentTypeName = FileConstants.FILE_EXT_NAME_ZIP;
        this.contentType = (String) contentTypeMap.get(contentTypeName);

        LogWritter.sysDebug("执行 doExport4FileList(response, files, encodeType)方法,参数为fileName:" + fileName +
                "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
        doExport4FileList(response, files, encodeType);
    }

    //对外提供的方法4  List files   此种情况只支持输出为zip
    public void exportFile(HttpServletResponse response, List bytes, List fileNames) throws IOException {
        //先将头信息设置为zip类型的
        this.contentTypeName = FileConstants.FILE_EXT_NAME_ZIP;
        this.contentType = (String) contentTypeMap.get(contentTypeName);

        LogWritter.sysDebug("执行 doExport4FileList(response, files, encodeType)方法,参数为fileName:" + fileName +
                "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
        doExport4ByteList(response, bytes,fileNames, encodeType);
    }

   
    //对外提供的方法5   String path
    public void exportFile(HttpServletResponse response, String path) throws IOException {
        if (!isZip && contentTypeName.equals(FileConstants.FILE_EXT_NAME_ZIP)) {
            FileInputStream in = new FileInputStream(path);
            doZippedExport(response, in, encodeType);
        } else {
            LogWritter.sysDebug("获得路径" + path + "上文件的InputStream.......");
            FileInputStream in = new FileInputStream(path);
            LogWritter.sysDebug("执行doExport(response, in, encodeType)方法,参数为fileName:" + fileName +
                    "; contentTypeName:" + contentTypeName + "; contentType:" + contentType);
            doExport(response, in, encodeType);
        }
    }

    //------------------------------私有方法---------------------------------
   /**
    * 初始化头类型Map
    */
    private void initContentTypeMap(){
        if (contentTypeMap.isEmpty()) {
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_CSV, FileConstants.CSV_CONTENT_TYPE);
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_ZIP, FileConstants.ZIP_CONTENT_TYPE);
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_XML, FileConstants.XML_CONTENT_TYPE);
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_TXT, FileConstants.TXT_CONTENT_TYPE);
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_DAT, FileConstants.DAT_CONTENT_TYPE);
            contentTypeMap.put(FileConstants.FILE_EXT_NAME_XLS, FileConstants.XLS_CONTENT_TYPE);
        }
    }
   
    //支持参数是file list 的export方法
    private void doExport4FileList(HttpServletResponse response,
                                   List files, String encoding) throws IOException {
        //Set http response header
        response.reset();
        response.setContentType(contentType + " charset=" + encoding);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + contentTypeName);

        //Zip and export.
        ZipOutputStream os = null;
        try {
            //取得zip输出流
            os = new ZipOutputStream(response.getOutputStream());
            //循环处理每一个file,将其放入zip中
            int i = 0;
            File theFile;
            for (i = 0; i < files.size(); i++) {
                theFile = (File) files.get(i);
                zip(os, theFile, theFile.getName());
            }
            os.flush();
        }
        catch (Exception e) {
            LogWritter.sysError("将fileList导出为zip文件时出现错误。 ", e);
            e.printStackTrace();
        }
        finally {
            closeStream(os);
        }
    }
 
   
    //支持参数是byte list 的export方法
    private void doExport4ByteList(HttpServletResponse response,
                                   List bytes, List fileNames, String encoding) throws IOException {
        //Set http response header
        response.reset();
        response.setContentType(contentType + " charset=" + encoding);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + contentTypeName);

        //Zip and export.
        ZipOutputStream os = null;
        try {
            //取得zip输出流
            os = new ZipOutputStream(response.getOutputStream());
            //循环处理每一个file,将其放入zip中
            int i = 0;
            int size = bytes.size();
            byte[] b;
            String fileName;
            for (i = 0; i < size; i++) {
                b = (byte[]) bytes.get(i);
                fileName = (String)fileNames.get(i);
                zip(os, b, fileName);
            }
            os.flush();
        }
        catch (Exception e) {
            LogWritter.sysError("将fileList导出为zip文件时出现错误。 ", e);
            e.printStackTrace();
        }
        finally {
            closeStream(os);
        }
    }
   
   
   
    /**
     * Export comma-separated-values file
     * @param response HttpServletResponse
     * @param bytes    byte[] Bytes from csv formatted string
     * @param encoding String Encoding for http content type.
     * @throws IOException
     */
    private void doExport(HttpServletResponse response, byte[] bytes,
                          String encoding) throws IOException {
        //Set http response header
        response.reset();
        response.setContentType(contentType + " charset=" + encoding);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + contentTypeName);

        //Do export
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(bytes));
        BufferedOutputStream bo = null;
        try {
            bo = new BufferedOutputStream(response.getOutputStream());
            byte[] buf = new byte[bufferSize];
            int b;
            while ((b = in.read(buf, 0, buf.length)) != -1) {
                bo.write(buf, 0, b);
            }
            bo.flush();
        } catch (IOException e) {
            LogWritter.sysError("[doExport] Export csv file exception ", e);
            throw e;
        } finally {
            closeStream(bo, in);
        }
    }

    /**
     * Export comma-separated-values file
     *
     * @param response HttpServletResponse
     * @param bytes    byte[] Bytes from csv formatted string
     * @param encoding String Encoding for http content type.
     * @throws IOException
     */
    private void doExport(HttpServletResponse response, InputStream in,
                          String encoding) throws IOException {
        //Set http response header
        response.reset();
        response.setContentType(contentType + " charset=" + encoding);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + contentTypeName);

        //Do export
        BufferedInputStream bin = new BufferedInputStream(in);
        BufferedOutputStream bo = null;
        try {
            bo = new BufferedOutputStream(response.getOutputStream());
            byte[] buf = new byte[bufferSize];
            int b;
            while ((b = bin.read(buf, 0, buf.length)) != -1) {
                bo.write(buf, 0, b);
            }
            bo.flush();
        } catch (IOException e) {
            LogWritter.sysError("[doExport] Export csv file exception ", e);
            throw e;
        } finally {
            closeStream(bo, in);
        }
    }

    /**
     * Multi-file zip and export
     * @param response  HttpServletResponse
     * @param bytesList List of several files in bytes form.
     * @param encoding  Encoding for http content type.
     * @throws IOException
     */
    private synchronized void doZippedExport(HttpServletResponse response,
                                             InputStream in, String encoding) throws
            IOException {
        if (in == null) {
            LogWritter.sysInfo("[doZippedExport] Nothing to be exported");
            return;
        }

        //Set http response header
        response.reset();
        response.setContentType(FileConstants.ZIP_CONTENT_TYPE + " charset=" + encoding);
        response.setHeader("Content-disposition", "filename=" + fileName + FileConstants.FILE_EXT_NAME_ZIP);

        //Zip and export.
        ZipOutputStream os = null;
        BufferedInputStream is = null;
        try {
            os = new ZipOutputStream(response.getOutputStream());
            LogWritter.sysInfo("fileName:" + fileName);
            os.putNextEntry(new ZipEntry(fileName));

            is = new BufferedInputStream(in);
            int b = 0;
            byte[] buf = new byte[bufferSize];
            while ((b = is.read(buf, 0, buf.length)) != -1) {
                os.write(buf, 0, b);
            }
            os.flush();
        }
        catch (Exception e) {
            LogWritter.sysError("[doZippedExport] Exception ", e);
        }
        finally {
            closeStream(os, is);
        }
    }

    /**
     * Multi-file zip and export
     * @param response  HttpServletResponse
     * @param bytesList List of several files in bytes form.
     * @param encoding  Encoding for http content type.
     * @throws IOException
     */
    private synchronized void doZipExport(HttpServletResponse response,
                                          File file, String encoding) throws
            IOException {
        //Set http response header
        response.reset();
        response.setContentType(FileConstants.ZIP_CONTENT_TYPE + " charset=" + encoding);
        response.setHeader("Content-disposition", "filename=" + fileName + FileConstants.FILE_EXT_NAME_ZIP);

        //Zip and export.
        ZipOutputStream os = null;
        try {
            os = new ZipOutputStream(response.getOutputStream());
            zip(os, file, file.getName());
            os.flush();
        }
        catch (Exception e) {
            LogWritter.sysError("[doZippedExport] Exception ", e);
            e.printStackTrace();
        }
        finally {
            closeStream(os);
        }
    }

    /**
     * zip 文件压缩
     * @param out  zip输出流
     * @param f    文件名
     * @param base 文件目录路径
     * @throws Exception
     */
    private void zip(ZipOutputStream out, File f, String base) throws Exception {
        LogWritter.sysDebug("Zipping  " + f.getName());
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + FileConstants.FILE_DIR_SPLIT_DIAGONAL));
            base = base.length() == 0 ? "" : base + FileConstants.FILE_DIR_SPLIT_DIAGONAL;
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            byte[] buf = new byte[bufferSize];
            int bb;
            while ((bb = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, bb);
            }
            in.close();
        }
    }

 /**
  * zip 文件压缩
  * @param out zip输出流
  * @param b byte[]
  * @param fileName 文件名
  * @throws Exception
  */
    private void zip(ZipOutputStream out, byte[] b, String fileName) throws Exception {
        LogWritter.sysDebug("Zipping  " + fileName);
  out.putNextEntry(new ZipEntry(fileName));
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(b));
        byte[] buf = new byte[bufferSize];
        int bb;
        while ((bb = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, bb);
        }
        in.close();
    }   
  
    /**
  * Export zipped comma-separated-values file
  *
  * @param response
  *            HttpServletResponse
  * @param bytes
  *            byte[] Bytes from csv formatted string
  * @param encoding
  *            String Encoding for http content type.
  * @throws IOException
  */
    private synchronized void doZippedExport(HttpServletResponse response,
                                             byte[] bytes, String encoding) throws IOException {
        //Set http response header
        response.reset();
        response.setContentType(FileConstants.ZIP_CONTENT_TYPE + " charset=" + encoding);
        response.setHeader("Content-disposition", "filename=" + fileName + FileConstants.FILE_EXT_NAME_ZIP);

        //Zip and export.
        ZipOutputStream os = null;
        BufferedInputStream is = null;
        try {
            os = new ZipOutputStream(response.getOutputStream());
            os.putNextEntry(new ZipEntry(fileName));
            is = new BufferedInputStream(new ByteArrayInputStream(bytes));
            int b = 0;
            byte[] buf = new byte[bufferSize];
            while ((b = is.read(buf, 0, buf.length)) != -1) {
                os.write(buf, 0, b);
            }
            os.flush();
        } catch (IOException e) {
            LogWritter.sysError("[doZippedExport] Exception ", e);
            throw e;
        } finally {
            closeStream(os, is);
        }
    }


    /**
     * Close byte stream
     * @param os OutputStream
     * @param is InputStream
     * @throws IOException
     */
    private void closeStream(OutputStream os, InputStream is) {
        try {
            if (os != null) {
                os.close();
                os = null;
            }
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
            LogWritter.sysError("Exception while closing Stream", e);
            e.printStackTrace();
        }
    }

   /**
    * 关闭输出流
    * @param os
    */
    private void closeStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
                os = null;
            }
        } catch (IOException e) {
            LogWritter.sysError("Exception while closing OutputStream", e);
            e.printStackTrace();
        }
    }
   
    //------------------------------属性和setter和getter方法---------------------------------------------
    private String contentTypeName; //向外提供的传入头类型名字 使用FileConstants中的类型 例FileConstants.FILE_EXT_NAME_CSV
    private String encodeType = FileConstants.CHARACTER_ENCODING_UTF8;  //enconding名字,默认为UTF8,若不指定 用默认
    private String fileName; //文件名,不含后缀名
    private String contentType; //导出文件的类型
    private int bufferSize = 2048; //Stream buffer size
    private static Map contentTypeMap = new HashMap();
    //当前导出的文件是否已经压缩,默认为未压缩
    private boolean isZip = false;

  
    /**
  * @return the isZip
  */
 public boolean isZip() {
  return isZip;
 }


 /**
  * @param isZip the isZip to set
  */
 public void setZip(boolean isZip) {
  this.isZip = isZip;
 }


 //get set 方法
    public String getEncodeType() {
        return encodeType;
    }

    public void setEncodeType(String encodeType) {
        this.encodeType = encodeType;
    }

    public String getContentTypeName() {
        return contentTypeName;
    }

    public void setContentTypeName(String contentTypeName) {
        this.contentTypeName = contentTypeName;
        //此处为映射
        this.contentType = (String) contentTypeMap.get(contentTypeName);
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    /**
     * Set stream buffer size
     *
     * @param bufferSize int New stream buffer size
     */
    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public int getBufferSize() {
        return bufferSize;
    }
   
    /**
     * Set exported file name
     * @param fileName The fileName to set.
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }


    public String getFileName() {
        return fileName;
    }
}

分享到:
评论

相关推荐

    java数据源导出WORD文档(包括图片、表格及文本)

    最近因项目开发的需要,整理了一份用JAVA导出WORD文档,其部署步骤如下: 1、将jacob-1.14.3-x86.dll放在服务器的系统盘(或运行本机的系统):\WINDOWS\system32目录下。 2、将jacob-1.14.3-x86.dll放在JDK 的 bin ...

    Java导出Word文件

    在Java编程环境中,导出Word文件是一项常见的任务,特别是在企业级应用中,如报表生成、文档自动化等场景。本文将详细讲解如何使用Java实现Word文件的导出,并结合提供的资源进行解析。 首先,Java导出Word文件通常...

    Java使用POI导出Word文档

    Java使用Apache POI库导出Word文档是一种常见的技术实践,特别是在企业级应用中,用于生成报告、合同或者自定义的数据输出。Apache POI是Apache软件基金会的一个开源项目,它提供了处理Microsoft Office格式(如Word...

    java freemarker导出word -包含多张图片导出

    在Java应用中,使用FreeMarker导出Word文档可以提供灵活的文本和数据结合的方式,尤其适用于生成报告、合同等复杂格式的文档。本篇将详细介绍如何使用FreeMarker与Java结合来导出包含多张图片的Word文档。 1. **...

    java根据word模板导出Word文件,插入图片表格都可以

    网络上的根据模板填充Word我都看过一些, 它们的功能在数据换行的时候用的是run对象的.addCarriageReturn()方法,或者是直接用\n实现换行。这些都不符合我的需求, 因为我要的是分段,而不是换行。换行的word导致另一...

    Java导出Word文档的实现.docx

    在Java开发中,导出Word文档是一项常见的任务,尤其在生成报表、报告或者合同等场合。本文将探讨如何使用Java高效地实现Word文档导出,主要聚焦于利用XDocReport和FreeMarker模板引擎的方式。 首先,Java中导出Word...

    java导出word并插入图片

    在Java编程环境中,导出Word文档并插入图片是一项常见的任务,尤其在自动化报告生成、数据可视化或文档处理的场景中。下面将详细讲解如何使用Java实现这个功能。 首先,我们需要一个能够操作Word文档的库。Apache ...

    java 使用 freemarker 导出word 包含 图片和动态的数据表,动态行和动态列

    在Java开发中,导出Word文档是一项常见的任务,特别是在企业级应用中,如报表生成、数据导出等。本篇文章将深入探讨如何使用FreeMarker模板引擎来生成包含图片和动态数据表的Word文档,尤其注重动态行和动态列的处理...

    java word导出功能实现

    在Java编程环境中,导出Word文档是一项常见的任务,特别是在企业级应用中,如报表生成、文档自动化等场景。Apache POI库是Java开发者用来处理Microsoft Office格式文件(如Word、Excel)的一个强大工具,尤其在读取...

    java带格式导出WORD文档

    本文将深入探讨如何利用Java技术结合Freemarker模板引擎实现带格式的Word文档导出,以满足客户对文档标准化、可打印且不变形的严格要求。 ### 1. 传统方法的局限性 在Java环境中,Apache POI和iText等库是常见的...

    java工程导出word文件的实例

    在Java编程环境中,导出Word文件是一项常见的任务,特别是在企业级应用中,如报告生成、数据导出等。本实例将介绍如何使用Java来创建和导出Word文档,以满足这些需求。 首先,我们需要了解Java中用于处理Word文档的...

    java 前台数据和echarts图表导出为word文件的jar

    首先,我们需要理解Java中导出Word文档的主要库Apache POI。Apache POI是Java社区中广泛采用的API,它允许程序员创建、修改和显示Microsoft Office格式的文件,包括Word(.docx)、Excel(.xlsx)和PowerPoint(....

    java实现导出excel、word、 pdf

    在Java编程中,导出Excel、Word和PDF是常见的数据呈现和报告生成需求。这些文件格式广泛用于数据存储、报表生成、文档分享等场景。以下将详细介绍如何使用Java实现这三种文件类型的导出。 首先,让我们关注Excel的...

    Java读取Word中的表格(Excel),并导出文件为Excel

    在Java编程中,有时我们需要处理来自不同文档格式的数据,例如从Word文档中提取表格内容,并将其转换成Excel文件。这通常涉及到使用Apache POI库,一个强大的API,用于读写Microsoft Office格式的文件,包括Word(....

    freemarker模板导出word循环图片表格源码和详细教程

    在本教程中,我们将探讨如何利用Freemarker模板来导出Word文档,并实现循环插入图片和表格的功能。这对于需要批量生成定制化报告或者文档的应用场景非常有用。 首先,我们需要了解Freemarker的基本语法。在...

    java生成word的实例 java导出Word文档的实例

    这个实例将带你了解如何在Java环境中使用API来创建和导出Word文档。以下是一些关键的知识点: 1. **Apache POI库**: Apache POI是Java社区开发的一个开源项目,提供了读写Microsoft Office格式文件的能力,包括...

    java导出word、excel、pdf、txt文件,同时兼容office2003和office2007

    1. **导出Word文档**: 使用XWPFDocument类创建和操作.docx文件。你可以创建XWPFParagraphs、XWPFTables等对象,填充文本、样式、图片等信息。例如,创建一个新的Word文档并写入文本: ```java XWPFDocument ...

    POI报表Word导出

    POI报表Word导出

    freemarker 导出word表格

    在本场景中,我们讨论的是如何利用FreeMarker来导出Word表格。这个过程通常涉及到以下步骤: 1. **创建Word模板**: 首先,你需要使用Microsoft Word创建所需的表格和格式。Word允许用户设计丰富的布局,包括...

Global site tag (gtag.js) - Google Analytics