数据导入和导出组件开发和单元测试

This commit is contained in:
weiweiw 2024-08-22 17:11:34 +08:00
parent ae35f350bf
commit 87b4ae1944
12 changed files with 581 additions and 93 deletions

View File

@ -136,6 +136,18 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- jfreechart -->
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -24,6 +24,13 @@ public @interface Excel
*/ */
public boolean isSequence() default false; public boolean isSequence() default false;
/**
* 是否是导入错误原因
* @return
*/
public boolean isErrorMessage() default false;
/**
/** /**
* 导出时在excel中排序 * 导出时在excel中排序
*/ */

View File

@ -0,0 +1,80 @@
package com.bonus.common.core.utils.poi;
import com.itextpdf.text.DocumentException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
public interface DocumentUtil {
/**
* 创建柱状图并插入到文档中
*
* @param title 图表标题
* @param categoryAxisLabel 目录轴的标签
* @param valueAxisLabel 数据轴的标签
* @param rowKeys 目录轴每行的key
* @param columnKeys 数据轴每列的key
* @param data 数据
* @return JFreeChart Jfreechart对象
*/
public default JFreeChart createBarChart(String title, String categoryAxisLabel, String valueAxisLabel,
String[] rowKeys, String[] columnKeys, double[][] data) throws IOException, DocumentException {
// 使用 JFreeChart 创建一个柱状图
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < rowKeys.length; i++) {
for (int j = 0; j < columnKeys.length; j++) {
dataset.addValue(data[i][j], rowKeys[i], columnKeys[j]);
}
}
JFreeChart barChart = ChartFactory.createBarChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true, true, false);
//将图表保存到字节数组输出流中
ByteArrayOutputStream chartOut = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(chartOut, barChart, 400, 400);
return barChart;
}
/**
* 创建饼状图并插入到文档中
*
* @param title 图表标题
* @param categories 目录轴的标签
* @param values 数据轴的标签
* @return JFreeChart Jfreechart对象
*/
public default JFreeChart createPieChart(String title, String[] categories, double[] values) throws IOException, DocumentException {
// 使用 JFreeChart 创建一个饼状图
DefaultPieDataset dataset = new DefaultPieDataset();
for (int i = 0; i < categories.length; i++) {
dataset.setValue(categories[i], values[i]);
}
JFreeChart pieChart = ChartFactory.createPieChart(title, dataset, true, true, false);
// 获取饼状图的 Plot 对象
PiePlot plot = (PiePlot) pieChart.getPlot();
// 设置标签格式
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
"{2}", new DecimalFormat("0"), new DecimalFormat("0%")));
plot.setSimpleLabels(true);
return pieChart;
}
}

View File

@ -84,6 +84,7 @@ public class ExcelUtil<T>
private static final int MAX_COMBO_STRING_LENGTH = 255; private static final int MAX_COMBO_STRING_LENGTH = 255;
private static final String TARGET_WITH_SEPARATOR = "."; private static final String TARGET_WITH_SEPARATOR = ".";
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
private static final String IMPORT_ERROR_MESSAGE = "导入错误原因";
public static final String FORMULA_REGEX_STR = "=|-|\\+|@"; public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
@ -183,6 +184,7 @@ public class ExcelUtil<T>
* 需要排除列属性 * 需要排除列属性
*/ */
public String[] excludeFields; public String[] excludeFields;
private String filedName;
public ExcelUtil(Class<T> clazz) public ExcelUtil(Class<T> clazz)
{ {
@ -448,7 +450,7 @@ public class ExcelUtil<T>
{ {
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
} }
else if (!attr.handler().equals(ExcelHandlerAdapter.class)) else if (!attr.handler().equals(com.bonus.common.core.utils.poi.ExcelHandlerAdapter.class))
{ {
val = dataFormatHandlerAdapter(val, attr, null); val = dataFormatHandlerAdapter(val, attr, null);
} }
@ -568,6 +570,7 @@ public class ExcelUtil<T>
{ {
fillExcelData(index, row); fillExcelData(index, row);
addStatisticsRow(); addStatisticsRow();
hideErrorMessageColumnIfEmpty();
} }
} }
} }
@ -965,7 +968,9 @@ public class ExcelUtil<T>
if(attr.isSequence()){ if(attr.isSequence()){
cell.setCellValue(sequence); cell.setCellValue(sequence);
} }
else if(attr.isErrorMessage() && StringUtils.isNotNull(value)){
cell.setCellValue(value.toString());
}
else if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) else if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
{ {
cell.setCellValue(parseDateToStr(dateFormat, value)); cell.setCellValue(parseDateToStr(dateFormat, value));
@ -1219,7 +1224,6 @@ public class ExcelUtil<T>
Cell cell = row.createCell(0); Cell cell = row.createCell(0);
cell.setCellStyle(styles.get("total")); cell.setCellStyle(styles.get("total"));
cell.setCellValue("合计"); cell.setCellValue("合计");
for (Integer key : keys) for (Integer key : keys)
{ {
cell = row.createCell(key); cell = row.createCell(key);
@ -1579,35 +1583,6 @@ public class ExcelUtil<T>
return exportExcelToLocalFile(sheetName); return exportExcelToLocalFile(sheetName);
} }
/**
* 对list数据源将其里面的数据导出到excel表单
doNothing().when(excelUtil).init(null, sheetName, title, Type.EXPORT);
doNothing().when(excelUtil).exportExcelToLocalFile(filePath);
// Act
excelUtil.exportExcelToLocalFile(filePath, null, sheetName, title);
// Assert
File file = new File(filePath);
assertTrue(file.exists());
// Clean up
file.delete();
}
@Excel
public static class User {
private Long id;
private String name;
private String sex;
private Integer age;
private Date birthday;
// Getters and Setters
}
}
*/
private AjaxResult exportExcelToLocalFile(String filePath) private AjaxResult exportExcelToLocalFile(String filePath)
{ {
OutputStream out = null; OutputStream out = null;
@ -1631,4 +1606,51 @@ public class ExcelUtil<T>
} }
return AjaxResult.error("导出Excel失败请联系网站管理员"); return AjaxResult.error("导出Excel失败请联系网站管理员");
} }
public void hideErrorMessageColumnIfEmpty() {
int columnIndex = getColumnIndexByFieldName(IMPORT_ERROR_MESSAGE);
if (columnIndex != -1) {
boolean isEmpty = isColumnEmptyExceptHeader(columnIndex);
if (isEmpty) {
sheet.setColumnHidden(columnIndex, true);
}
}
}
private int getColumnIndexByFieldName(String fieldName) {
for (int columnIndex = 0; columnIndex <= sheet.getRow(0).getLastCellNum(); columnIndex++) {
if (fieldName.equals(sheet.getRow(0).getCell(columnIndex).getStringCellValue())) {
return columnIndex;
}
}
// 如果没有找到返回-1
return -1;
}
private boolean isColumnEmptyExceptHeader( int columnIndex) {
// 假设列头在第一行
int headerRowIndex = 0;
Row headerRow = sheet.getRow(headerRowIndex);
if (headerRow == null) {
// 如果列头所在行不存在则认为整列都为空
return true;
}
// 获取最后一行的索引
int lastRowNum = sheet.getLastRowNum();
for (int rowIndex = headerRowIndex + 1; rowIndex <= lastRowNum; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);
if (currentRow == null) {
continue; // 如果当前行不存在则检查下一行
}
Cell cell = currentRow.getCell(columnIndex);
if (cell != null) {
String errorMessage = cell.getStringCellValue();
if (StringUtils.isNotBlank(errorMessage)) {
return false;
}
}
}
// 如果遍历完所有行都没有找到非空单元格则返回true
return true;
}
} }

View File

@ -0,0 +1,163 @@
package com.bonus.common.core.utils.poi;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class PdfUtil implements DocumentUtil {
private final Document document;
private final PdfWriter writer;
/**
* 初始化 PDF 文档
* @param pdfPath PDF 本地文件路径
* @throws DocumentException 文档异常处理
* @throws IOException IO 异常处理
*/
public PdfUtil(String pdfPath) throws DocumentException, IOException {
document = new Document();
writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
}
/**
* 初始化 PDF 文档
* @param response http响应
* @throws DocumentException 文档异常处理
* @throws IOException IO 异常处理
*/
public PdfUtil (HttpServletResponse response) throws DocumentException, IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"generated.pdf\"");
document = new Document();
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
}
/**
* 添加段落
* @param text 段落文本
* @param font 字体样式
* @throws DocumentException 文档异常处理
*/
public Paragraph addParagraph(String text, Font font) throws DocumentException {
Paragraph paragraph = new Paragraph(text, font);
document.add(paragraph);
return paragraph;
}
/**
* 添加表格
* @param headers 表头数组
* @param content 表格内容
* @param numCols 表格列数
* @throws DocumentException 文档异常处理
*/
public void addTable(String[] headers, String[][] content, int numCols) throws DocumentException {
PdfPTable table = new PdfPTable(numCols);
for (String header : headers) {
PdfPCell cell = new PdfPCell(new Phrase(header));
// cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(cell);
}
for (String[] row : content) {
for (String cellData : row) {
table.addCell(cellData);
}
}
document.add(table);
}
/**
* 添加图片
* @param imagePath 图片文件路径
* @throws IOException IO 异常处理
* @throws DocumentException 文档异常处理
*/
public void addImage(String imagePath) throws IOException, DocumentException {
Image image = Image.getInstance(imagePath);
image.scaleToFit(500, 500); // 根据需求调整图片大小
document.add(image);
}
/**
* 添加段落并设置样式
*
* @param text 段落文本
* @param bold 是否加粗
* @param italic 是否斜体
* @param fontSize 字体大小
* @throws DocumentException 文档异常处理
*/
public void addStyledParagraph(String text, boolean bold, boolean italic, int fontSize) throws DocumentException {
Font font = new Font(Font.FontFamily.TIMES_ROMAN, fontSize);
if (bold) {
font.setStyle(Font.BOLD);
}
if (italic) {
font.setStyle(Font.ITALIC);
}
addParagraph(text, font);
}
/**
* 创建饼状图并插入到文档中
*
* @param title 图表标题
* @param categories 目录轴的标签
* @param values 数据轴的标签
*/
public void addPieChart( String title, String[] categories, double[] values) throws IOException, DocumentException {
// 使用 JFreeChart 创建一个饼状图
JFreeChart pieChart = createPieChart(title, categories, values);
addChartToDocument(pieChart);
}
/**
* 创建柱状图并插入到文档中
* @param title 图表标题
* @param categoryAxisLabel 目录轴的标签
* @param valueAxisLabel 数据轴的标签
* @param rowKeys 目录轴每行的key
* @param columnKeys 数据轴每列的key
* @param data 数据
*/
public void addBarChart(String title, String categoryAxisLabel, String valueAxisLabel,
String[] rowKeys, String[] columnKeys, double[][] data) throws IOException, DocumentException {
JFreeChart barChart = createBarChart(title, categoryAxisLabel, valueAxisLabel, rowKeys, columnKeys, data);
addChartToDocument(barChart);
}
/**
* JFreeChart 图表添加到 PDF 文档中
*
* @param chart JFreeChart 对象
* @throws IOException IO 异常处理
* @throws DocumentException 文档异常处理
*/
private void addChartToDocument(JFreeChart chart) throws IOException, DocumentException {
int width = 500;
int height = 400;
ByteArrayOutputStream chartOutput = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(chartOutput, chart, width, height);
Image chartImage = Image.getInstance(chartOutput.toByteArray());
chartImage.scaleToFit(width, height);
document.add(chartImage);
}
/**
* 关闭文档
*/
public void close() {
document.close();
}
}

View File

@ -1,74 +1,168 @@
package com.bonus.common.core.utils.poi;
import com.itextpdf.text.DocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.util.Units; import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*; import org.apache.poi.xwpf.usermodel.*;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import java.io.FileInputStream; import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream; import java.io.*;
import java.io.IOException; import java.math.BigInteger;
import java.io.InputStream;
public class WordUtil { public class WordUtil implements DocumentUtil {
private XWPFDocument document; private final XWPFDocument document;
/**
* 创建一个Word文档并添加文字图片表格等元素
*/
public WordUtil() { public WordUtil() {
this.document = new XWPFDocument(); this.document = new XWPFDocument();
} }
// 创建段落 /**
public void addParagraph(String text, int fontSize) { * 获取文档对象
*/
public XWPFDocument getDocument() {
return document;
}
/**
* 添加一个文字段落设置字体和大小
*
* @param text 文本内容
* @param fontSize 字体大小
* @param font 默认字体为宋体
* @return XWPFParagraph 段落对象可以用于更改段落其他属性
*/
public XWPFParagraph addParagraph(String text, int fontSize, String font) {
XWPFParagraph paragraph = document.createParagraph(); XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun(); XWPFRun run = paragraph.createRun();
run.setText(text); run.setText(text);
run.setFontSize(fontSize); run.setFontSize(fontSize);
run.setFontFamily(font);
return paragraph;
} }
// 插入图片 /**
public void insertImage(String imgFilePath, int width, int height) { * 创建一个表格并插入到文档中
*
* @param rows 行数
* @param cols 列数
* @param content rows*cols的数组
* @param columnWidths 每列的宽度单位是 twips1 twip = 1/20 point
*/
public XWPFTable addTable(int rows, int cols, String[][] content, int[] columnWidths) {
XWPFTable table = document.createTable(rows, cols);
for (int i = 0; i < rows; i++) {
XWPFTableRow row = table.getRow(i);
for (int j = 0; j < cols; j++) {
XWPFTableCell cell = row.getCell(j);
if (content != null && content.length > i && content[i].length > j) {
cell.setText(content[i][j]);
} else {
cell.setText("Row " + (i + 1) + ", Column " + (j + 1));
}
// 设置每个单元格的宽度
cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(columnWidths[j]));
}
}
return table;
}
/**
* 创建图片并插入到文档中
*
* @param imgFilePath 图片本地路径
* @param width 图片宽
* @param height 图片高
*/
public void insertImage(String imgFilePath, int width, int height) throws RuntimeException {
try (InputStream is = new FileInputStream(imgFilePath)) { try (InputStream is = new FileInputStream(imgFilePath)) {
XWPFParagraph paragraph = document.createParagraph(); XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun(); XWPFRun run = paragraph.createRun();
run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, imgFilePath, Units.toEMU(width), Units.toEMU(height)); run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, imgFilePath, Units.toEMU(width), Units.toEMU(height));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); throw new RuntimeException("insertImage exception", e);
} }
} }
// 创建表格 /**
public void createTable(int rows, int cols) { * 创建柱状图并插入到文档中
XWPFTable table = document.createTable(rows, cols); *
for (int row = 0; row < rows; row++) { * @param title 图表标题
XWPFTableRow tableRow = table.getRow(row); * @param categoryAxisLabel 目录轴的标签
for (int cell = 0; cell < cols; cell++) { * @param valueAxisLabel 数据轴的标签
XWPFTableCell tableCell = tableRow.getCell(cell); * @param rowKeys 目录轴每行的key
tableCell.setText("Row " + row + ", Cell " + cell); * @param columnKeys 数据轴每列的key
} * @param data 数据
} */
public void addBarChart(String title, String categoryAxisLabel, String valueAxisLabel,
String[] rowKeys, String[] columnKeys, double[][] data) throws IOException, DocumentException, InvalidFormatException {
JFreeChart barChart = createBarChart(title, categoryAxisLabel, valueAxisLabel, rowKeys, columnKeys, data);
ByteArrayOutputStream chartOut = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(chartOut, barChart, 400, 400);
// 将图表字节数组转为输入流并插入到文档中
ByteArrayInputStream chartIn = new ByteArrayInputStream(chartOut.toByteArray());
// Add chart to document
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.addPicture(chartIn, XWPFDocument.PICTURE_TYPE_PNG, "bar_chart.png", Units.toEMU(400), Units.toEMU(400));
} }
// 保存文档 /**
public void saveDocument(String filePath) { * 创建饼状图并插入到文档中
try (FileOutputStream out = new FileOutputStream(filePath)) { *
document.write(out); * @param title 图表标题
} catch (IOException e) { * @param categories 目录轴的标签
e.printStackTrace(); * @param values 数据轴的标签
} */
public void addPieChart( String title, String[] categories, double[] values) throws IOException, DocumentException, InvalidFormatException {
JFreeChart pieChart = createPieChart(title, categories, values);
//将图表保存到字节数组输出流中
ByteArrayOutputStream chartOut = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(chartOut, pieChart, 400, 400);
ByteArrayInputStream chartIn = new ByteArrayInputStream(chartOut.toByteArray());
//将图表字节数组转为输入流并插入到文档中
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.addPicture(chartIn, XWPFDocument.PICTURE_TYPE_PNG, "pie_chart.png", Units.toEMU(400), Units.toEMU(400));
} }
// 关闭文档 /**
public void closeDocument() { * 保存文档
try { * @param filePath 文档本地路径
document.close(); */
} catch (IOException e) { public void saveDocumentToLocal(String filePath) throws IOException {
e.printStackTrace(); FileOutputStream out = new FileOutputStream(filePath);
} document.write(out);
} }
public static void main(String[] args) { /**
WordUtil wordUtil = new WordUtil(); * 保存文档到HttpServletResponse对象中
wordUtil.addParagraph("这是一个段落。", 16); * @param response 返回数据
wordUtil.insertImage("path/to/image.png", 200, 200); */
wordUtil.createTable(3, 3); public void saveDocumentToResponse(HttpServletResponse response) throws IOException{
wordUtil.saveDocument("example.docx"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
wordUtil.closeDocument(); response.setCharacterEncoding("utf-8");
OutputStream out = response.getOutputStream();
document.write(out);
} }
/**
* 关闭文档
* 完成保存结束后一定调用此方法否则会产生内容泄露的风险
*/
public void closeDocument() throws IOException {
document.close();
}
} }

View File

@ -1,27 +1,26 @@
package com.bonus.common.core.utils.poi; package com.bonus.common.core.utils.poi;
import com.bonus.common.core.utils.poi.ExcelUtil;
import org.junit.Test; import org.junit.Test;
import com.bonus.common.core.annotation.Excel;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class ExcelUtilTests { public class ExcelUtilTests {
@Test @Test
public void testImportExcel() { public void testImportExcel() {
String currentPath = System.getProperty("user.dir"); String currentPath = System.getProperty("user.dir");
System.out.println("当前执行路径: " + currentPath); System.out.println("当前执行路径: " + currentPath);
ExcelUtil excelUtil = new ExcelUtil<Person>(Person.class); ExcelUtil<Person> excelUtil = new ExcelUtil<Person>(Person.class);
currentPath +="/src/test/java/com/bonus/common/core/utils/poi/test.xlsx"; currentPath +="/src/test/java/com/bonus/common/core/utils/poi/test.xlsx";
try (FileInputStream fileInputStream = new FileInputStream(currentPath)) { try (FileInputStream fileInputStream = new FileInputStream(currentPath)) {
List<Person> persionList = excelUtil.importExcel(fileInputStream); List<Person> persionList = excelUtil.importExcel(fileInputStream);
assertTrue(persionList.size() == 4); assertEquals(4, persionList.size());
String sex = persionList.get(0).getSex();
} catch (FileNotFoundException e) { assertEquals("1", sex);
throw new RuntimeException(e);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -30,17 +29,30 @@ public class ExcelUtilTests {
@Test @Test
public void testExportExcel() { public void testExportExcel() {
String currentPath = System.getProperty("user.dir"); String currentPath = System.getProperty("user.dir");
System.out.println("当前执行路径: " + currentPath); ExcelUtil<Person> excelUtil = new ExcelUtil<Person>(Person.class);
ExcelUtil excelUtil = new ExcelUtil<Person>(Person.class); Person p1 = new Person("admin",10,"0");
Person p1 = new Person("admin",10); Person p2 = new Person("admin2",20,"1");
Person p2 = new Person("admin2",20);
List <Person> personList = new ArrayList<>(); List <Person> personList = new ArrayList<>();
personList.add(p1); personList.add(p1);
personList.add(p2); personList.add(p2);
currentPath +="/src/test/java/com/bonus/common/core/utils/poi/testExport.xlsx"; currentPath +="/src/test/java/com/bonus/common/core/utils/poi/testExport.xlsx";
excelUtil.exportExcelToLocalFile(currentPath,personList, "sheet1", null); excelUtil.exportExcelToLocalFile(currentPath,personList, "sheet1", null);
}
@Test
public void testExportExcelWithImportErrorMessage() {
String currentPath = System.getProperty("user.dir");
System.out.println("当前执行路径: " + currentPath);
ExcelUtil<Person> excelUtil = new ExcelUtil<Person>(Person.class);
Person p1 = new Person("admin",10,"");
p1.setImportErrorMessage("用户名存在");
Person p2 = new Person("admin2",20,"");
p2.setImportErrorMessage("数据格式不正确");
List <Person> personList = new ArrayList<>();
personList.add(p1);
personList.add(p2);
currentPath +="/src/test/java/com/bonus/common/core/utils/poi/testExportWithImportErrorMsg.xlsx";
excelUtil.exportExcelToLocalFile(currentPath,personList, "sheet1", null);
} }

View File

@ -0,0 +1,24 @@
package com.bonus.common.core.utils.poi;
import com.itextpdf.text.DocumentException;
import org.junit.Test;
import java.io.IOException;
public class PdfUtilTests {
@Test
public void testPdf() throws IOException, DocumentException, InterruptedException {
String currentPath = System.getProperty("user.dir");
String fileName = currentPath+ "/src/test/java/com/bonus/common/core/utils/poi/testExport1.pdf";
PdfUtil pdfUtil = new PdfUtil(fileName);
pdfUtil.addStyledParagraph("测试文字", true, false, 12);
pdfUtil.addTable(new String[] { "姓名", "年龄" }, new String[][] { { "张三", "18" }, { "李四", "19" } }, 2);
pdfUtil.addBarChart("柱状图", "月份", "数量", new String[] { "1", "2", "3" }, new String[] { "1", "2", "3" }, new double[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
pdfUtil.addPieChart("饼状图", new String[] { "1月份", "2月份", "3月份" }, new double[] { 1, 2, 3 });
pdfUtil.addParagraph("测试文字", null);
pdfUtil.addStyledParagraph("测试文字样式", true, true, 12);
String imagePath = currentPath + "/src/test/java/com/bonus/common/core/utils/poi/register.jpg";
pdfUtil.addImage(imagePath);
pdfUtil.close();
}
}

View File

@ -3,33 +3,52 @@ package com.bonus.common.core.utils.poi;
import com.bonus.common.core.annotation.Excel; import com.bonus.common.core.annotation.Excel;
public class Person { public class Person {
@Excel(name = "序号", isSequence = true, cellType = Excel.ColumnType.NUMERIC, type = Excel.Type.EXPORT) @Excel(name = "序号", isSequence = true, type = Excel.Type.EXPORT)
int sequence; int sequence;
@Excel(name = "姓名", cellType = Excel.ColumnType.STRING) @Excel(name = "姓名", cellType = Excel.ColumnType.STRING)
String name; String name;
@Excel(name = "年龄", isStatistics = true, cellType = Excel.ColumnType.NUMERIC) @Excel(name = "年龄", cellType = Excel.ColumnType.NUMERIC)
int age; int age;
@Excel(name = "性别", readConverterExp="0=男,1=女,2=未知")
String sex;
@Excel(name = "导入错误原因", isErrorMessage=true, cellType = Excel.ColumnType.STRING,type = Excel.Type.EXPORT )
String importErrorMessage;
@Excel(name = "头像", cellType = Excel.ColumnType.IMAGE, type = Excel.Type.EXPORT, width = 14,height = 14)
String imagePath = "http://192.168.0.56:18083/file/2024/08/15/hao_20240815100236A002.jpg";
// 公共无参构造函数 // 公共无参构造函数
public Person() { public Person() {
} }
// 带参数的构造函数 // 带参数的构造函数
public Person(String name, int age) { public Person(String name, int age, String sex) {
this.name = name; this.name = name;
this.age = age; this.age = age;
this.sex = sex;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {this.name = name;}
this.name = name;
}
public int getAge() {return age;} public int getAge() {return age;}
public void setAge(int age) { public void setAge(int age) {
this.age = age; this.age = age;
} }
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setImportErrorMessage(String importErrorMessage) {
this.importErrorMessage = importErrorMessage;
}
public String getImportErrorMessage() {return importErrorMessage;}
} }

View File

@ -0,0 +1,55 @@
package com.bonus.common.core.utils.poi;
import com.itextpdf.text.DocumentException;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
public class WordUtilTests {
@Test
public void testWord() {
String currentPath = System.getProperty("user.dir");
String fileName = currentPath+"/src/test/java/com/bonus/common/core/utils/poi/testExport.docx";
WordUtil wordUtil = new WordUtil();
wordUtil.addParagraph("hello world这是一个正文", 14, "宋体");
wordUtil.addTable(2, 3, new String[][] { { "1", "2", "3" }, { "4", "5", "6" } }, new int []{3000,3000,3000});
XWPFDocument document = wordUtil.getDocument();
try {
wordUtil.addBarChart("柱状图", "", "数量", new String[]{"计划", "实际"}, new String[]{"第一季度", "第二季度", "第三季度"}, new double[][]{{1, 2,3}, {4, 5,6}});
wordUtil.addPieChart("饼状图", new String[]{"1月份", "2月份", "3月份"}, new double[]{1, 2, 3});
wordUtil.saveDocumentToLocal(fileName);
wordUtil. closeDocument();
} catch (Exception ignored){
System.out.print("异常发生" + ignored.getMessage());
}
File file = new File(fileName);
assertTrue(file.exists());
}
@Test
public void testWordWithImage() {
String currentPath = System.getProperty("user.dir");
String fileName = currentPath+"/src/test/java/com/bonus/common/core/utils/poi/testExport1.docx";
WordUtil wordUtil = new WordUtil();
wordUtil.addParagraph("hello world这是一个正文", 14, "宋体");
wordUtil.addTable(2, 3, new String[][] { { "1", "2", "3" }, { "4", "5", "6" } }, new int []{3000,3000,3000});
XWPFDocument document = wordUtil.getDocument();
try {
String imagePath = currentPath + "/src/test/java/com/bonus/common/core/utils/poi/register.jpg";
wordUtil.insertImage(imagePath, 400, 400);
wordUtil.saveDocumentToLocal(fileName);
wordUtil. closeDocument();
} catch (Exception ignored){
System.out.print("异常发生" + ignored.getMessage());
}
File file = new File(fileName);
assertTrue(file.exists());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB