小弟最近在项目中,遇到用poi技术将excel模板读取,加上一列之后,写入某些值,再写回原EXCEL。
直接贴代码吧。上面的注释也很清晰。
package com.caojiulu.poi;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
*
* @author caojiulu
*
*/
public class Main {
public static void main(String[] args) {
Workbook workBook = null;
FileInputStream fis = null;
FileOutputStream fos = null;
String filePath = "";
try {
//读取指定路径下的excel
fis = new FileInputStream(filePath);
//加载到workBook
workBook = new HSSFWorkbook(fis);
//获取第一个sheet页
Sheet sheetAt = workBook.getSheetAt(0);
//获取excel有多少条数据
int rowSize = sheetAt.getLastRowNum()+1;
//遍历所有的数据
for (int i = 0; i < rowSize; i++) {
//获取第I行的数据
Row row = sheetAt.getRow(i);
//创建第I行 第4列的单位格
Cell cell = row.createCell(3);
//设置值
cell.setCellValue("caojiulu");
//设置单位格的风格
CellStyle style = workBook.createCellStyle();
//创建字体
Font font = workBook.createFont();
//设置字体的颜色
font.setColor(Font.COLOR_RED);
style.setFont(font);
cell.setCellStyle(style);
}
//将更改后的excel写回去
fos = new FileOutputStream(filePath);
workBook.write(fos);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(workBook!=null){
try {
workBook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
转载请附上原文链接!谢谢
标签:apache,POI,excel,catch,usermodel,poi,workBook,import,xls From: https://blog.51cto.com/u_14906615/5899441