package com.grid.util;
import com.grid.pojo.databean.monitor.SimpleDataBean;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName ExportUtils
* @Description: TODO
* @Author Winy
* @Date 2022/03/31
* @Version V1.0.0
* Modification History:
* Date Author Version Description
* ----------------------------------------------------------------------*
* 2022/03/31 Winy v1.0.0 初次创建
**/
public class ExportUtils {
public static void main(String[] args) throws FileNotFoundException {
List<SimpleDataBean> list=new ArrayList<>();
for (int i=0;i<100000;i++){
list.add(new SimpleDataBean(Float.parseFloat(Math.random()+""),"2021-12-12 03:00:00"));
}
String filename="workbook111.pdf";
FileOutputStream out = new FileOutputStream("E:/"+filename);
export(list,new String[]{"value","time"},new String[]{"数据","时间"},"pdf",out);
}
/**
* 列表导出多格式文档
* @param list 数据源
* @param param 参数 数据源中的属性名称
* @param topName 列名
* @param downtype 文件格式 pdf,excel,word
* @param out 输出流
*/
public static <T> void export(List<T> list, String[] param, String[] topName, String downtype, OutputStream out) {
try {
switch (downtype) {
case "excel":
exportExcel(objectToMap(list),param,topName,out);
return;
case "pdf":
exportPdf(objectToMap(list),param,topName,out);
return;
case "word":
exportWord(objectToMap(list),param,topName,out);
}
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void exportExcel(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
// 表头加粗居中样式
HSSFCellStyle style = wb.createCellStyle();
org.apache.poi.ss.usermodel.Font f = wb.createFont();
f.setBold(true);
style.setFont(f);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// 内容左对齐,宽度自适应
HSSFCellStyle contentS = wb.createCellStyle();
contentS.setAlignment(CellStyle.ALIGN_CENTER);
contentS.setWrapText(true);
contentS.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
contentS.setBorderBottom(HSSFCellStyle.BORDER_THIN);
contentS.setBorderTop(HSSFCellStyle.BORDER_THIN);
contentS.setBorderLeft(HSSFCellStyle.BORDER_THIN);
contentS.setBorderRight(HSSFCellStyle.BORDER_THIN);
HSSFRow row = sheet.createRow(0);
//存储最大列宽
Map<Integer, Integer> maxWidth = new HashMap<>();
//写入表头
for (int i = 0; i < topName.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(topName[i]);
cell.setCellStyle(style);
maxWidth.put(i, cell.getStringCellValue().getBytes().length * 256 + 200);
}
//写入数据
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i+1);
Map<String, Object> m = list.get(i);
for (int j = 0; j < param.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(contentS);
cell.setCellValue(m.get(param[j]) + "");
sheet.setColumnWidth(j, 8 * 512);
int length = cell.getStringCellValue().getBytes().length * 256 + 200;
//这里把宽度最大限制到15000
if (length > 15000) {
length = 15000;
}
maxWidth.put(j, Math.max(length, maxWidth.get(j)));
}
}
// 列宽自适应
for (int i = 0; i < topName.length; i++) {
sheet.setColumnWidth(i, maxWidth.get(i));
}
try {
wb.write(out);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void exportPdf(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
// 第一步,实例化一个document对象
Document document = new Document();
// 第三步,设置字符
BaseFont bfChinese = null;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
Font fontZH = new Font(bfChinese, 12.0F, 0);
// 第四步,将pdf文件输出到磁盘
try {
PdfWriter.getInstance(document, out);
} catch (DocumentException e) {
e.printStackTrace();
}
// 第五步,打开生成的pdf文件
document.open();
// 第六步,设置内容
// 创建table,注意这里的2是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列
PdfPTable table = new PdfPTable(topName.length);
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
for (String p:topName) {
table.addCell(new Paragraph(p, fontZH));
}
for (Map<String,Object> l:list) {
for (String p:param) {
table.addCell(new Paragraph(l.get(p).toString(), fontZH));
}
}
try {
document.add(table);
document.add(new Paragraph("\n"));
} catch (DocumentException e) {
e.printStackTrace();
}
// 第七步,关闭document
document.close();
}
private static void exportWord(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
XWPFDocument document=new XWPFDocument();
XWPFTable table = document.createTable();
//列宽自动分割
CTTblWidth infoTableWidth=table.getCTTbl().addNewTblPr().addNewTblW();
infoTableWidth.setType(STTblWidth.DXA);
infoTableWidth.setW(BigInteger.valueOf(9072));
//自适应窗口
//第一行 列名
XWPFTableRow row_top=table.getRow(0);
for (int i=0;i<topName.length;i++) {
XWPFTableCell cell=row_top.getCell(i);
if (cell==null)
cell=row_top.addNewTableCell();
cell.setText(topName[i]);
}
//填充数据
for (Map<String,Object> l:list) {
XWPFTableRow row=table.createRow();
for (int i=0;i<topName.length;i++) {
row.getCell(i).setText(l.get(param[i]).toString());
}
}
try {
document.write(out);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* List<object>转List<map>
*/
private static <StationDeviceDataBean> List<Map<String, Object>> objectToMap(List<StationDeviceDataBean> reorder) {
List<Map<String, Object>> lm = new ArrayList<>();
try {
for (Object obj : reorder) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
Field[] sFields = obj.getClass().getSuperclass().getDeclaredFields();
for (Field field : sFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
lm.add(map);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return lm;
}
public static String getSuffix(String downType) {
switch (downType){
case "pdf":return "pdf";
case "excel":return "xlsx";
case "word":return "docx";
}
return "xlsx";
}
}
【POI】列表数据导出word、pdf、excel格式文档
最新推荐文章于 2023-05-30 16:10:08 发布