第一步:引入依赖包
<!-- tools -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.12</version>
</dependency>
第二步:上代码
基础变量的准备
public static String first_file_Path="";
public static String second_file_Path="";
public static String previous_excel_path="";
public static String final_excel_path= "";
public static final String first_sheet_name = "";
public static final String second_sheet_name = "";
准备读写的文件
File file_template = new File(previous_excel_path);
File file_final = new File(final_excel_path);
FileUtils.copyFile(file_template, file_final);
FileInputStream把文件转换成文件输入流
FileInputStream fileInputStream = new FileInputStream(file_template);
通过文件输入流创建Workbook
OPCPackage opcPackage= OPCPackage.open(fileInputStream);
Workbook workbook = WorkbookFactory.create(opcPackage);
特殊处理
String[] firstFileStr=FileUtils.readFileToString(new File(first_file_Path),"utf-8").split("\n");
String[] secondFileStr =FileUtils.readFileToString(new File(second_file_Path),"utf-8").split("\n");
通过Workbook获取对应的sheet
Sheet sheet1 = workbook.getSheet(first_sheet_name);
Sheet sheet2 = workbook.getSheet(second_sheet_name);
sheet里面写入值
/sheet1
for(int i=0;i<configYamls.length;i++){
Row row=sheet1.getRow(i+1);
if(row==null){
row=sheet1.createRow(i+1);
}
Cell c = row.getCell(0);
if(c == null){
c = row.createCell(0);
}
c.setCellType(Cell.CELL_TYPE_STRING);
c.setCellValue(configYamls[i]);
}
//sheet2
for(int i=0;i<inputTemplates.length;i++){
Row row=sheet2.getRow(i+1);
if(row==null){
row=sheet2.createRow(i+1);
}
Cell c = row.getCell(0);
if(c == null){
c = row.createCell(0);
}
c.setCellType(Cell.CELL_TYPE_STRING);
c.setCellValue(inputTemplates[i]);
}
输出流
ByteArrayOutputStream workbook_os = new ByteArrayOutputStream();
写入到输出流
workbook.write(workbook_os);
FileOutputStream写入文件
FileOutputStream fileOutputStream = new FileOutputStream(file_final);
fileOutputStream.write(workbook_os.toByteArray());
关闭文件流
fileOutputStream.close();
fileInputStream.close();