(目前只更新导出pdf表格)
导出pdf表格
1、依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2、工具类:
import com.crunii.micro.common.exception.BusinessException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @Filename: PdfUtils
* @Author: sheng.wanping
* <li>Date: 2022/8/1 15:40</li>
* <li>Version: 1.0</li>
* <li>Content: create</li>
*/
public class PdfUtils {
// 定义全局的字体静态变量
private static Font titlefont;
private static Font textfont;
static {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 8, Font.BOLD);
textfont = new Font(bfChinese, 8, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Filename: PdfUtils pdf工具类
* @Author: sheng.wanping
* <li>Date: 2022/8/1 15:40</li>
* <li>Version: 1.0</li>
* <li>Content: create</li>
*/
public class PdfUtils {
/**
* 用于返回 简单列表PDF表格
* @param response
* @param tableName 表名
* @param list 数据列表
* @param map 中英文map(key为标题,value为字段英文名;注意:map是有顺序的,可用LinkedHashMap)
* @param <T>
*/
public static <T> void pdfSingleTable(HttpServletResponse response, String tableName, List<T> list, Map<String, String> map) {
// 1、从map中获取字段中文名和英文名
List<String> valueList = new ArrayList<>(); // 存表格所有数据
List<String> fieldEnList = new ArrayList<>(); // 字段英文名
for (Map.Entry<String, String> entry : map.entrySet()) {
valueList.add(entry.getKey());
fieldEnList.add(entry.getValue());
}
// 2、用反射根据字段名获取值
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < fieldEnList.size(); j++) {
Field field = null;
String strValue = "";
try {
field = list.get(i).getClass().getDeclaredField(fieldEnList.get(j));
field.setAccessible(true);
Object value = field.get(list.get(i));
if (value != null) {
if (value instanceof Date) {
strValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else {
strValue = String.valueOf(value);
}
} else {
strValue = "";
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
valueList.add(strValue);// 字段值
}
}
}
// 3、返回pdf
try {
// 3-1.新建document对象
Document document = new Document(PageSize.A4);
// 3-2.建立一个书写器
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tableName+".pdf", "UTF-8"));
ServletOutputStream out = response.getOutputStream();
PdfWriter.getInstance(document, out);
// 3-3.打开文档
document.open();
// 3-4、查询数据库数据,并存入list中
// 3-5、设置单元格宽度
List<Integer> mergeCellList = new ArrayList<>();
int idx = 0;
while (idx < (list.size() + 1) * fieldEnList.size()) {
idx++;
mergeCellList.add(1);
}
// 3-6.创建表格
PdfPTable table = new PdfPTable(fieldEnList.size());
for (int i = 0; i < mergeCellList.size(); i++) {
PdfPCell cell = new PdfPCell(); // 创建行
cell.setColspan(mergeCellList.get(i)); // 合并单元格
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
cell.setPhrase(new Phrase(valueList.get(i), new Font(bfChinese, 8, Font.NORMAL)));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell); // 添加单元格内容
}
// 3-7、向文档中添加内容
document.add(table);
// 3-8、关闭文档
document.close();
out.close();
}catch (Exception e){
e.printStackTrace();
throw new BusinessException("导出pdf失败");
}
}
/**
* 返回一个字节数组输出流
* @param list 数据列表
* @param map 中英文map(key为标题,value为字段英文名;注意:map是有顺序的,可用LinkedHashMap)
* @param <T>
*/
public static <T> ByteArrayOutputStream getByteArray(List<T> list, Map<String, String> map) {
// 1、从map中获取字段中文名和英文名
List<String> valueList = new ArrayList<>(); // 存表格所有数据
List<String> fieldEnList = new ArrayList<>(); // 字段英文名
for (Map.Entry<String, String> entry : map.entrySet()) {
valueList.add(entry.getKey());
fieldEnList.add(entry.getValue());
}
// 2、用反射根据字段名获取值
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < fieldEnList.size(); j++) {
Field field = null;
String strValue = "";
try {
field = list.get(i).getClass().getDeclaredField(fieldEnList.get(j));
field.setAccessible(true);
Object value = field.get(list.get(i));
if (value != null) {
if (value instanceof Date) {
strValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else {
strValue = String.valueOf(value);
}
} else {
strValue = "";
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
valueList.add(strValue);// 字段值
}
}
}
// 3、返回pdf
try {
// 3-1.新建document对象
Document document = new Document(PageSize.A4);
// 2.建立一个书写器
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter.getInstance(document, os);
// 3-3.打开文档
document.open();
// 3-4、查询数据库数据,并存入list中
// 3-5、设置单元格宽度
List<Integer> mergeCellList = new ArrayList<>();
int idx = 0;
while (idx < (list.size() + 1) * fieldEnList.size()) {
idx++;
mergeCellList.add(1);
}
// 3-6.创建表格
PdfPTable table = new PdfPTable(fieldEnList.size());
for (int i = 0; i < mergeCellList.size(); i++) {
PdfPCell cell = new PdfPCell(); // 创建行
cell.setColspan(mergeCellList.get(i)); // 合并单元格
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
cell.setPhrase(new Phrase(valueList.get(i), new Font(bfChinese, 8, Font.NORMAL)));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell); // 添加单元格内容
}
// 3-7、向文档中添加内容
document.add(table);
document.close();
return os;
}catch (Exception e){
e.printStackTrace();
throw new BusinessException("导出pdf失败");
}
}
}
3、测试代码
private static final Map<String, String> BUDGE_MAP = new LinkedHashMap<>();
static {
BUDGE_MAP.put("主设备", "mainEquipmentExpense");
BUDGE_MAP.put("天线", "aerialExpense");
BUDGE_MAP.put("电源", "powerExpense");
}
public void testPdf(HttpServletResponse response) {
List<Object> list = testDao.getData;// 查询数据列表
PdfUtils.pdfSingleTable(response, "表名", list, BUDGE_MAP);// 导出pdf表格
}