https://blog.csdn.net/qq_40981804/article/details/105166189
- 导入excel解析所需要的jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
- 结构
类名 说明
HSSFWorkbook Excel的文档对象
HSSFSheet Excel的表单
HSSFRow Excel的行
HSSFCell Excel的格子单元
HSSFFont Excel字体
HSSFDataFormat 格子单元的日期格式
HSSFHeader Excel文档Sheet的页眉
HSSFFooter Excel文档Sheet的页脚
HSSFCellStyle 格子单元样式
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表
- 代码
package com.document.exe;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author haizhuangbu
* @Date
* @function
* @mark
*/
@Slf4j
public class ExUtil {
@SneakyThrows
public static void createEx() throws FileNotFoundException {
String[] header = {"name", "age", "sex"};
List<String[]> data = new ArrayList();
String[] da = {"1", "2", "3"};
data.add(da);
// 实例化
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建工作簿
HSSFSheet sheet = workbook.createSheet("工作簿1");
// create table header
setTitle(workbook, sheet, header);
// save data
setData(sheet, data);
File file1 = new File("name1.xls");
if (file1.exists()) {
file1.delete();
}
FileOutputStream file = new FileOutputStream("name1.xls");
workbook.write(file);
}
// 创建表头
public static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
// 表头 第一行
HSSFRow row = sheet.createRow(0);
// 设置行高列宽
for (int i = 0; i < str.length; i++) {
sheet.setColumnWidth(i, 15 * 256);
}
// 设置居中加粗 格式化日期
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 设置字体
HSSFFont font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 11);
// create font weight
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// create font name
font.setFontName("Courier New");
// create auto /n
cellStyle.setWrapText(true);
cellStyle.setFont(font);
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dyy h:mm"));
// create table header
for (int i = 0; i < str.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(str[i]);
cell.setCellStyle(cellStyle);
}
}
/**
* 表格赋值
*/
public static void setData(HSSFSheet sheet, List<String[]> data) {
for (int i = 0; i < data.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
for (int i1 = 0; i1 < data.get(i).length; i1++) {
row.createCell(i1).setCellValue(data.get(i)[i1]);
}
}
}
public static void main(String[] args) throws FileNotFoundException {
createEx();
}
}