Java:导出word,浏览器下载

WordUtil类

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.xjl.student.model.Person;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.util.ResourceUtils;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 报告导出
 */
public class WordUtil {

    /**
     * 导出word
     * @param filepath
     * @throws Exception
     */
    public void exportWord(String filepath, List<Person> list) throws Exception {
        // 创建word文档,并设置纸张的大小
        Document document = new Document(PageSize.A4);
        try {
            //建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
            RtfWriter2.getInstance(document, new FileOutputStream(filepath));
            document.open();
            // 设置字体
            BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            // 主标题字体风格
            Font titleFont = new Font(font, 24, Font.BOLD);
            // 副标题字体风格
            Font subTitleFont = new Font(font, 16, Font.BOLD);
            // 正文字体风格
            Font contextFont = new Font(font, 12, Font.NORMAL);

            Paragraph title = new Paragraph("测试报告导出");
            // 设置标题格式对齐方式
            title.setAlignment(Element.ALIGN_CENTER);
            title.setFont(titleFont);
            document.add(title);

            // 获取数据
//            List<Person> list = getStudentData();

            Paragraph title1 = new Paragraph("一、学生信息表");
            // 设置标题格式对齐方式
            title1.setAlignment(Element.ALIGN_LEFT);
            title1.setFont(subTitleFont);
            document.add(title1);

            // 创建有三列的表格
            Table table = new Table(3);
            table.setBorderWidth(1);
            table.setBorderColor(Color.BLACK);
            table.setPadding(0);
            table.setSpacing(0);

            // 添加表头,合并单元格
            Cell cell = new Cell("报告导出");
            cell.setHeader(true);
            // 设置表格为三列
            cell.setColspan(3);
            // 设置表格为一行
            cell.setRowspan(1);
            table.addCell(cell);
            // 表头结束
            table.endHeaders();

            table.addCell("学号");
            table.addCell("姓名");
            table.addCell("年龄");
            // 将数据加入表中
            insertData(table, list);
            document.add(table);
            //******************************************
            Paragraph title2 = new Paragraph("二、iText介绍");
            // 设置标题格式对齐方式
            title2.setAlignment(Element.ALIGN_LEFT);
            title2.setFont(subTitleFont);
            document.add(title2);
            String contextString = "iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。";
            Paragraph context = new Paragraph(contextString);
            // 正文格式左对齐
            context.setAlignment(Element.ALIGN_LEFT);
            context.setFont(contextFont);
            // 离上一段落(标题)空的行数
            context.setSpacingBefore(5);
            // 设置第一行空的列数
            context.setFirstLineIndent(20);
            document.add(context);
            //**************添加图片****************************
            Paragraph title3 = new Paragraph("三、图片");
            // 设置标题格式对齐方式
            title3.setAlignment(Element.ALIGN_LEFT);
            title3.setFont(subTitleFont);
            document.add(title3);
            Image img = Image.getInstance("D:/app/OnePiece.jpg");
            img.setAbsolutePosition(10, 10);
            // 设置图片显示位置
            img.setAlignment(Image.ALIGN_CENTER);
            // 表示显示的大小为原尺寸的20%
            img.scalePercent(20);
            document.add(img);
            //*******************表二***********************
            Paragraph title4 = new Paragraph("四、学生信息表");
            // 设置标题格式对齐方式
            title4.setAlignment(Element.ALIGN_LEFT);
            title4.setFont(subTitleFont);
            document.add(title4);
            // 创建有三列的表格
            Table table2 = new Table(3);
            table2.setBorderWidth(1);
            table2.setBorderColor(Color.BLACK);
            table2.setPadding(0);
            table2.setSpacing(0);
            // 添加表头
            table2.addCell("学号");
            table2.addCell("姓名");
            table2.addCell("年龄");

            // 将数据加入表中
            insertData(table2, list);

            document.add(table2);

            document.close();
            System.out.println("word已经导出到:" + filepath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加数据到表中
     * @param table
     * @param list
     * @throws Exception
     */
    private void insertData(Table table, List<Person> list) throws Exception {
        for (int i = 0; i < list.size(); i++) {
            Person stu = list.get(i);
            // 创建单元格,并设置各个列中实际数据的值
            Cell cell = new Cell();
            // 设置表格为三列
            cell.setColspan(3);
            // 设置表格行数
            cell.setRowspan(list.size());
            // 添加数据
            table.addCell("id:"+ stu.getId());
            table.addCell("name:" + stu.getName());
            table.addCell("age:"+ stu.getAge());
        }
    }

    /**
     * 创造数据
     * @return
     */
    private static List<Person> getStudentData() {
        List<Person> list = new ArrayList<Person>();
        for (int i = 1; i <= 3; i++) {
            Person stu = new Person();
            stu.setId(i);
            stu.setName("学生_"+i);
            stu.setAge(10+i);
            list.add(stu);
        }
        return list;
    }

    public static void main(String[] args) throws Exception {
        WordUtil wordDemo = new WordUtil();
        String nameString = DateFormatUtils.format(new Date(), "yyMMdd_HHmmss");
        String filepath = "D:/app/Test_" + nameString + ".doc";
        List<Person> list = getStudentData();
        wordDemo.exportWord(filepath, list);
    }
}

Person类

import lombok.Data;
@Data
public class Person {
    private int id;
    private String name;
    private int age;
}

浏览器下载代码

import com.xjl.student.model.Person;
import com.xjl.student.util.WordUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * exportWord
 * http://localhost:10086/exportCase/exportWord
 */
@RestController
@RequestMapping("/exportCase")
public class ExportWordController {
    @RequestMapping(value = "exportWord",method = RequestMethod.GET)
    public void exportExcel(HttpServletResponse response) throws Exception {
        String dateTime = DateFormatUtils.format(new Date(), "yyMMdd_HHmmss");
        String filepath = "/app/ExportWord_" + dateTime + ".doc";
        WordUtil wordUtil = new WordUtil();
        List<Person> list = getStudentData();
        wordUtil.exportWord(filepath, list);
        OutputStream output = null;
        try {
            //清空缓存
            response.reset();
            // 定义浏览器响应表头,并定义下载名
            String fileName = URLEncoder.encode("ExportWord_"+dateTime+".doc", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileName);
            //定义下载的类型,标明是word文件
            response.setContentType("application/msword;charset=UTF-8");
            //把创建好的word写入到输出流

            FileInputStream inputStream = new FileInputStream(filepath);
            byte[] buffer = new byte[inputStream.available()];

            inputStream.read(buffer);

            output = response.getOutputStream();
            output.write(buffer);

            //随手关门
            output.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //造假数据
    private static List<Person> getStudentData() {
        List<Person> list = new ArrayList<Person>();
        for (int i = 1; i <= 3; i++) {
            Person stu = new Person();
            stu.setId(i);
            stu.setName("学生_"+i);
            stu.setAge(10+i);
            list.add(stu);
        }
        return list;
    }
}

注:
(1)pom:iText2.1.7、iText-rtf2.1.7、itextpdf5.4.3、itext-asian5.2.0
(2)上述未用到数据库,但可自行查询数据再放入list中即可
(3)浏览器下载地址IP、端口自行查询
(4)效果图如下:
《Java:导出word,浏览器下载》

    原文作者:話吥哆先森丶
    原文地址: https://blog.csdn.net/spirit_8023/article/details/83273920
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞