利用Apache POI操作Excel

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

1、maven配置Apache POI

pom.xml中配置POIjar包坐标

 1 <!-- 配置Apache POI -->
 2         <dependency>
 3             <groupId>org.apache.poi</groupId>
 4             <artifactId>poi</artifactId>
 5             <version>4.1.0</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.apache.poi</groupId>
 9             <artifactId>poi-ooxml</artifactId>
10             <version>4.1.0</version>
11         </dependency>
12         <dependency>
13             <groupId>org.apache.poi</groupId>
14             <artifactId>poi-ooxml-schemas</artifactId>
15             <version>4.1.0</version>
16         </dependency>

2、测试

 1 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 2 import org.apache.poi.ss.usermodel.*;
 3 import org.junit.Test;
 4 
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 
 9 public class POITest {
10 
11     @Test
12     public void run() throws IOException {
13         // 1、创建一个工作簿
14         Workbook wb = new HSSFWorkbook();
15         // 2、创建一个sheet
16         Sheet sheet = wb.createSheet();
17         // 3、创建行对象
18         Row row = sheet.createRow(2);
19         // 4、创建单元格
20         Cell cell = row.createCell(3);
21         // 5、设置单元格内容
22         cell.setCellValue("Apache POI操作Excel测试");
23         // 单元格样式
24         CellStyle cellStyle = wb.createCellStyle();
25         // 字体
26         Font font = wb.createFont();
27         font.setFontName("华文隶书");
28         font.setFontHeightInPoints((short)20);
29         cellStyle.setFont(font);
30         // 6、设置字体样式
31         cell.setCellStyle(cellStyle);
32         // 7、保存,关闭流
33         OutputStream os = new FileOutputStream("E:\\POITest.xls");
34         wb.write(os);
35         os.close();
36     }
37 }

3、结果

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

猜你喜欢

转载自www.cnblogs.com/alphajuns/p/11373251.html