利用Apache POI操作Excel

时间:2023-03-09 03:53:42
利用Apache POI操作Excel

最近在做接口,有个功能是利用Excel导入汽车发动机所需零件信息到线上系统中。简单回顾一下之前学过的用java操作Excel。

1、maven配置Apache POI

pom.xml中配置POIjar包坐标

 <!-- 配置Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>

2、测试

 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.junit.Test; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; public class POITest { @Test
public void run() throws IOException {
// 1、创建一个工作簿
Workbook wb = new HSSFWorkbook();
// 2、创建一个sheet
Sheet sheet = wb.createSheet();
// 3、创建行对象
Row row = sheet.createRow(2);
// 4、创建单元格
Cell cell = row.createCell(3);
// 5、设置单元格内容
cell.setCellValue("Apache POI操作Excel测试");
// 单元格样式
CellStyle cellStyle = wb.createCellStyle();
// 字体
Font font = wb.createFont();
font.setFontName("华文隶书");
font.setFontHeightInPoints((short)20);
cellStyle.setFont(font);
// 6、设置字体样式
cell.setCellStyle(cellStyle);
// 7、保存,关闭流
OutputStream os = new FileOutputStream("E:\\POITest.xls");
wb.write(os);
os.close();
}
}

3、结果

利用Apache POI操作Excel

这个操作是比较简单的,工作需要做的是:首先验证是否是Excel文件,其次验证Excel中的内容,然后读取上传的Excel文件内容(第一行的标题及每行内容),最后将读取的内容插入相关的数据库表。