2021-03-06 16:15工具类集合整理
2021-03-12 14:32更新:导出的Excel中添加了能够在cecel中添加图片的功能
以下Demo均进行过测试,如有错误,还请各位指出改进!
java 导出 Excel ,能替换字体和图片
逻辑思想,采用替换的逻辑,就是通过一个map把Excel模板中字段进行相应的替换。
相应工具类如下:
使用测试excel模板文件:公众号:知识浅谈 后台回复 Excel模板
对应的依赖
引入以下依赖:
<properties>
<poi.version>4.1.2</poi.version>
</properties>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
工具类
package com.englishcode;
import com.sun.media.sound.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
//import org.apache.tomcat.util.http.fileupload.FileUtils;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
/**
* @author YinLei
* @version 1.0
* @date 2021/3/1 13:05
*/
public class JavaToExcelUtils {
public void outExcel(String inPath, String outPath, Map params, int sheetnum) throws IOException, InvalidFormatException {
//inPath是模板路径 outPath是生成的新的excel的路径
InputStream is = new FileInputStream(new File(inPath)); //读取模板文件
Workbook wb = WorkbookFactory.create(is); //
Sheet sheet = wb.getSheetAt(sheetnum);//获取Excel的工作表sheet,下标从0开始,因为一个excel文件中可能有多个sheet
int trLength = sheet.getLastRowNum();//获取Excel的行数
//int a=0;
for (int i = 0; i < trLength; i++) {
Row row = sheet.getRow(i);//获取Excel的行,下标从0开始
if (row == null) {
//若行为空,则遍历下一行
continue;
}
int minColIx = row.getFirstCellNum(); //获取该行中列的最左边的下标
int maxColIx = row.getLastCellNum(); //获取该行中列的最右边的下标
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
//遍历该行
Cell cell = row.getCell(colIx);//获取指定单元格,单元格从左到右下标从0开始
// int flag =0;
if(cell!=null) //当单元格为空的时候,不处理
{
cell.setCellType(CellType.STRING); //设置单元格的类型
String runText = cell.getStringCellValue(); //获取单元格中的内容
if (runText.equals("")){
continue;
}
// System.out.println(cell);
Matcher matcher = this.matcher(runText); //把单元格中原始的内容作为要匹配的字符串
if (matcher.find()) {
//当有匹配的的字符串
while ((matcher = this.matcher(runText)).find()) {
//group(1)返回第一组匹配到的字符串,就是正则匹配规则中的第一个()中的匹配
if(String.valueOf(params.get(matcher.group(1))).equals("null"))
break;
else {
runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
// flag=1;
// System.out.println(runText);
}
//把该表格中的原始数据替换成param中key是matcher.group(1)的value值
}
if (runText.endsWith(".jpg")||runText.endsWith(".png")){
//替换图片
cell.setCellValue("");
byte[] bt = FileUtils.readFileToByteArray(new File(runText));
int pictureIdx;
if(runText.endsWith(".jpg"))
pictureIdx