Java excel poi 读取已有文件 ,动态插入一列数据
/**
* 读取已有文件 ,动态插入一列数据
* @param args
*/
public static void main(String[] args) {
try {
//读取文件
File file = new File("D:\\testworkbook.xls");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
//获取excel
HSSFWorkbook workbook = new HSSFWorkbook(in);
//获取第二个sheet
HSSFSheet sheet = workbook.getSheetAt(1);
String[] list = {"第一行", "第二行", "第三行"};
//动态写一列数据
for (int i = 0; i < list.length; i++) {
//第一种写法
// HSSFRow row = sheet.createRow(0);
// Cell cell = row.createCell(0);
// cell.setCellValue("第一行第一列");
//第二种写法 创建行
Row row = sheet.createRow(i);
//设置第一列的值
row.createCell(0).setCellValue(list[i]);
}
//写入文件
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
}catch (Exception e){
}
}