POI 操作excel
导包
<!-- 07版本excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- 03版本excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
用法
03版本的excel文件名 *.xls
07版本的excel文件名 *.xlsx
//创建工作薄
Workbook workbook03 = new HSSFWorkbook();
Workbook workbook07 = new XSSFWorkbook();
HSSFWorkbook : 03版本的Excel工作薄对象
XSSFWorkbook : 07版本的Excel工作薄对象
测试
写入导出Excel
Test1.java
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
String PATH = "G:\\IdeaProjects\\Open_excel";
@Test
public void test() throws IOException {
//创建工作薄
Workbook workbook = new HSSFWorkbook();
//工作薄
Sheet sheet1 = workbook.createSheet("第一个sheet");
//创建一个行
Row row1 = sheet1.createRow(0);//第一行
Cell cell11 = row1.createCell(0);
cell11.setCellValue("今日收入");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("时间");
Row row2 = sheet1.createRow(1);//第一行
Cell cell21 = row2.createCell(0);
cell21.setCellValue("15");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(new DateTime().toString());
FileOutputStream fos = new FileOutputStream(PATH+"\\03xls.xls");
workbook.write(fos);
fos.close();
System.out.println("生成好了");
}
}