WordUtil类java
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 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 list = getStudentData();
Paragraph title1 = new Paragraph("1、学生信息表");
// 设置标题格式对齐方式
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("2、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("3、图片");
// 设置标题格式对齐方式
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("4、学生信息表");
// 设置标题格式对齐方式
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 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 getStudentData() {
List list = new ArrayList();
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 list = getStudentData();
wordDemo.exportWord(filepath, list);
}
}
Person类web
import lombok.Data;
@Data
public class Person {
private int id;
private String name;
private int age;
}
浏览器下载代码spring
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 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 getStudentData() {
List list = new ArrayList();
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.七、iText-rtf2.1.七、itextpdf5.4.三、itext-asian5.2.0
(2)上述未用到数据库,但可自行查询数据再放入list中便可
(3)浏览器下载地址IP、端口自行查询
(4)效果图以下:
数据库