1. 创建Excel
1.1 创建新Excel工作簿
引入poi依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo01 {
public static void main(String[] args) throws Exception {
// 创建一个工作簿
Workbook wb = new HSSFWorkbook();
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\创建一个Excel工作簿.xls");
wb.write(fileOutputStream);
// 工作簿写出流
wb.close();
}
}
运行代码
1.2 创建新sheet页
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo02 {
public static void main(String[] args) throws Exception {
// 创建一个工作簿
Workbook wb = new HSSFWorkbook();
// 创建一个sheet页
wb.createSheet("这是第一个sheet的名字");
wb.createSheet("这是第二个sheet的名字");
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\创建sheet.xls");
// 工作簿写出流
wb.write(fileOutputStream);
wb.close();
}
}
运行代码
1.3 创建单元格
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo03 {
public static void main(String[] args) throws Exception {
// 创建一个工作簿
Workbook wb = new HSSFWorkbook();
// 创建一个sheet页
Sheet sheet = wb.createSheet("这是第一个sheet的名字");
// 创建单元格并设置内容
// 创建第一行
Row row = sheet.createRow(0);
row.createCell(0).setCellValue(1); // 第一列
row.createCell(1).setCellValue(1.2); // 第二列
row.createCell(2).setCellValue("字符串"); // 第三列
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\创建sheet.xls");
// 工作簿写出流
wb.write(fileOutputStream);
wb.close();
}
}
运行代码
2. 创建时间格式单元格
2.1 创建一个时间格式的单元格
Java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.util.Date;
/**
* @Description: 创建时间格式单元格
* @author: lh
*/
public class Demo04 {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(0);
row.createCell(0).setCellValue(new Date());
// 设置单元格日期格式
CreationHelper creationHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();// 单元格样式
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss"));
Cell cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
2.2 遍历工作簿的行和列并获取单元格内容
java代码
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
/**
* @Description: 遍历单元格
* @author: lh
*/
public class Demo05 {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
POIFSFileSystem fs = new POIFSFileSystem(fileInputStream);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
if (sheet == null) {
return;
}
// 遍历row
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
if (row == null) {
continue;
}
// 遍历cell
for (int j = 0; j <= row.getLastCellNum(); j++) {
if (row.getCell(j) == null) {
continue;
}
System.out.print(" " + getValue(row.getCell(j)));
}
System.out.println();
}
}
/**
* 获取不同类型单元格类型的值
* @param cell 单元格
* @return 单元格内容
*/
private static String getValue(HSSFCell cell) {
switch (cell.getCellType()) {
case NUMERIC:
return Double.toString(cell.getNumericCellValue());
case BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case STRING:
return cell.getStringCellValue();
// Add cases for other cell types as needed...
default:
System.out.println("Unsupported cell type");
return "";
}
}
}
运行结果
2.4 文本提取
Java代码
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
/**
* @Description: 文本提取
* @author: lh
*/
public class Demo06 {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
POIFSFileSystem fs = new POIFSFileSystem(fileInputStream);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fs);
ExcelExtractor excelExtractor = new ExcelExtractor(hssfWorkbook);
excelExtractor.setIncludeSheetNames(false); //不需要sheet页
System.out.println(excelExtractor.getText());
fileInputStream.close();
fs.close();
}
}
运行结果
3. 单元格处理
3.1 单元格对齐方式
Java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
/**
* @Description: 单元格对齐方式
* @author: lh
*/
public class Demo07 {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(0);
row.setHeightInPoints(30);
// 创建单元格对齐方式
createCell(workbook, row, (short) 0, HorizontalAlignment.CENTER, VerticalAlignment.CENTER, "单元格对齐方式1");
createCell(workbook, row, (short) 1, HorizontalAlignment.LEFT, VerticalAlignment.BOTTOM, "单元格对齐方式2");
createCell(workbook, row, (short) 2, HorizontalAlignment.RIGHT, VerticalAlignment.TOP, "单元格对齐方式3");
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
private static void createCell(Workbook workbook, Row row, short column, HorizontalAlignment align, VerticalAlignment valign, String value) {
Cell cell = row.createCell(column);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(align);
cellStyle.setVerticalAlignment(valign);
cell.setCellValue(value);
cell.setCellStyle(cellStyle);
}
}
运行结果
3.2 单元格边框处理
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
/**
* @Description: 单元格边框处理
* @author: lh
*/
public class Demo08 {
public static void main(String[] args) throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(1);
row.setHeightInPoints(30);
Cell cell = row.createCell(1);
cell.setCellValue("单元格边框处理");
// 单元格边框处理
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop(BorderStyle.THIN); // 顶部边框样式
cellStyle.setTopBorderColor(IndexedColors.RED.getIndex()); // 顶部边框颜色
cellStyle.setBorderLeft(BorderStyle.MEDIUM); // 左边边框样式
cellStyle.setLeftBorderColor(IndexedColors.BLUE.getIndex()); // 左边边框颜色
cellStyle.setBorderRight(BorderStyle.MEDIUM); // 右边边框样式
cellStyle.setRightBorderColor(IndexedColors.GREEN.getIndex()); // 右边边框颜色
cellStyle.setBorderBottom(BorderStyle.MEDIUM); // 底部边框样式
cellStyle.setBottomBorderColor(IndexedColors.BROWN.getIndex()); // 底部边框颜色
cell.setCellStyle(cellStyle);
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
3.3 单元格填充色和颜色操作
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
/**
* @Description: 设置单元格颜色
* @author: lh
*/
public class Demo09 {
public static void main(String[] args) throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(1);
row.setHeightInPoints(30);
// 设置单元格颜色
Cell cell = row.createCell(1);
cell.setCellValue("单元格边框处理");
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); //背景色
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
Cell cell1 = row.createCell(2);
cell1.setCellValue("单元格边框处理1");
CellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setFillForegroundColor(IndexedColors.RED.getIndex()); //前景色
cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell1.setCellStyle(cellStyle1);
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
3.4 单元格合并
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
/**
* @Description: 单元格合并
* @author: lh
*/
public class Demo10 {
public static void main(String[] args) throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(1);
row.setHeightInPoints(30);
// 合并单元格
Cell cell = row.createCell(1);
cell.setCellValue("合并单元格");
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
4. 字体处理
4.1 字体处理
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
/**
* @Description: 字体处理
* @author: lh
*/
public class Demo11 {
public static void main(String[] args) throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(1);
row.setHeightInPoints(30);
// 创建一个字体处理类
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 24);
font.setFontName("宋体");
font.setItalic(true);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
Cell cell = row.createCell((short) 1);
cell.setCellValue("hello world");
cell.setCellStyle(cellStyle);
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
4.2 单元格中使用换行
java代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
/**
* @Description: 单元格换行
* @author: lh
*/
public class Demo12 {
public static void main(String[] args) throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个sheet页");
Row row = sheet.createRow(1);
row.setHeightInPoints(30);
Cell cell = row.createCell(2);
cell.setCellValue("我要换行 \n 成功了吗?");
CellStyle cellStyle = workbook.createCellStyle();
// 设置可以换行
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");
workbook.write(fileOutputStream);
workbook.close();
}
}
运行结果
5. 综合示例
// excel导入
@Transactional
public Result<?> import(Model model) throws IOException
{
// 获取上传附件
String attId = attachFileAppService.handleAttFiles(Collections.singletonList(model));
if (StringUtil.isEmpty(attId))
{
throw new NormalRuntimeException(ModelCodeConstants.ATTACHMENT_LOST);
}
Workbook workbook = null;
InputStream data = null;
try
{
// 获取Excel文件流
UploadAttachFileInfo uploadAttachFileInfo = attachFileAppService.downloadFile(attId);
// 文件格式校验
checkType(uploadAttachFileInfo);
data = uploadAttachFileInfo.getData();
workbook = ExcelUtils.getExcelWorkbook(data);
Sheet sheet = workbook.getSheet(ModelCodeConstants."读取sheet的名字");
if (CommonUtil.isEmpty(sheet))
{
return Result.fail(ModelCodeConstants.ERROR_TITLE);
}
// 表头检验
checkTitle(sheet);
// 空表检验
if (sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 1)
{
return Result.fail(ModelCodeConstants.EMPTY_FILE);
}
// 数据导入- 从第四行开始
int startRowIndex = 4;
Iterator<Row> iterator = sheet.iterator();
for (int i = 0; i < startRowIndex; i++)
{
iterator.next();
}
List<XXX> list = new ArrayList<>();
List<XXX> errList = new ArrayList<>();
while (iterator.hasNext())
{
Row row = iterator.next();
String xxx = getValue(row.getCell(0));
String yyy = getValue(row.getCell(1));
String zzz = getValue(row.getCell(2));
String aaa = getValue(row.getCell(3));
// 导入数据规则校验
StringJoiner joiner = new StringJoiner(",");
checkBody(xxx, yyy, zzz, aaa, joiner);
XXX err = new XXX();
if (joiner.length() != 0)
{
err.setErrMsg(joiner);
// 错误信息添加
errList.add(err);
} else
{
XXX x = new XXX();
// 入库信息添加
list.add(x);
// 数据入库
service.add();
}
}
if (CommonUtil.isNotEmpty(errList))
{
//把原信息和错误信息写回去
String uuid = writeErrExcel(errList);
return Result.fail("数据导入不成功,点击下载错误信息!").setData(uuid);
}
} catch (Exception e)
{
e.printStackTrace();
return Result.fail(e.getMessage());
} finally
{
assert workbook != null;
workbook.close();
data.close();
}
return Result.success();
}
/**
* 文件格式校验 以xls或者xlsx结尾
*/
private static void checkType(UploadAttachFileInfo uploadAttachFileInfo)
{
AttachFileInfo fileInfo;
fileInfo = uploadAttachFileInfo.getFileInfo();
if (!fileInfo.getFileName().endsWith(ModelCodeConstants.EXCEL_SUFFIX_XLS)
&& !fileInfo.getFileName().endsWith(ModelCodeConstants.EXCEL_SUFFIX_XLSX))
{
throw new NormalRuntimeException("文件格式有误!");
}
}
/**
* 校验表头是否正确
*/
private static void checkTitle(Iterator<Row> rowIterator)
{
Row headerRow = rowIterator.next();
Cell xxxx = headerRow.getCell(0);
Cell yyyy = headerRow.getCell(1);
if (!"xxxx".equals(xxxx.getStringCellValue()) || !"yyyy".equals(yyyy.getStringCellValue()))
{
throw new NormalRuntimeException(ModelCodeConstants.ERROR_TITLE);
}
}
/**
* 填写错误信息excel
*/
private String writeErrExcel(List<XXX> errList) throws Exception
{
// 读取错误信息模板
String rootPath = SpringContextConfig.getOptRootPath();
String filePath = rootPath + FilePathConst.TEMPLATE_FILE_PATH + FileNameConst.WBS_CODE_ERROR_FILE_NAME;
File file = ResourceUtils.getFile(filePath);
InputStream inputStream = Files.newInputStream(file.toPath());
// 处理导入错误信息数据
Workbook workbook = ExcelUtils.getExcelWorkbook(inputStream);
Sheet sheet = workbook.getSheet(ModelCodeConstants.TEMPLATE_ESTIMATE_DETAILS);
int startRow = 4; // 从第五行开始写入数据
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true); // 自动换行
for (int i = startRow; i < errList.size() + startRow; i++)
{
Row row = sheet.createRow(i);
XXX rowData = errList.get(i - startRow); // 获取当前行数据
String xxx = rowData.getLevel();
String yyy = rowData.getWbsCode();
String zzz = rowData.getWbsDescribe();
String aaa = rowData.getWbsAmount();
String errMsg = rowData.getErrMsg();
row.createCell(0).setCellValue(xxx);
row.createCell(1).setCellValue(yyy);
row.createCell(2).setCellValue(zzz);
row.getCell(2).setCellStyle(cellStyle);
row.createCell(3).setCellValue(aaa);
row.createCell(4).setCellValue(errMsg);
row.getCell(4).setCellStyle(cellStyle);
}
// Excel文件写到目标路径下
String uuid = CommonUtil.getUUID();
String distPath = AttachServerConfig.AttachServerTempPath + "/" + FilePathConst.ERROR_FILE_PATH + "/" + uuid
+ "/" + FileNameConst.WBS_CODE_ERROR_FILE_NAME;
ExcelWriter write = new ExcelWriter(sheet);
write.setDestFile(new File(distPath));
write.flush();
write.close();
InputStream distStream = new FileInputStream(distPath);
uuid = attachFileAppService.uploadFile(distStream, FileNameConst.WBS_CODE_ERROR_FILE_NAME,
FileModelTypeEnum.导入失败信息.getModel(), uuid, "xlsx");
return uuid;
}
// 枚举常量类
public interface ModelCodeConstants
{
public final String ATTACHMENT_LOST = "导入附件丢失或未找到,请重新上传!";
public final String ERROR_TITLE = "表头信息错误,请使用标准模板文件导入!";
public final String EMPTY_FILE = "上传文件内容为空,请确认!";
}
// excel工具类
public class ExcelUtils
{
/**
* 读取工作区域,传入流文件
* @param input
* @return
*/
public static Workbook getExcelWorkbook(InputStream input)
{
Workbook workbook = null;
try
{
workbook = WorkbookFactory.create(input);
} catch (EncryptedDocumentException | InvalidFormatException | IOException e)
{
e.printStackTrace();
}
return workbook;
}
/**
* 获取不同类型单元格类型的值
* @param cell 单元格
* @return 单元格内容
*/
private static String getValue(HSSFCell cell) {
switch (cell.getCellType()) {
case NUMERIC:
return Double.toString(cell.getNumericCellValue());
case BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case STRING:
return cell.getStringCellValue();
// Add cases for other cell types as needed...
default:
System.out.println("Unsupported cell type");
return "";
}
}
}