POI操作Excel

简单的读写 excel(xlsx),如果是xls格式,只需换成HSSFXXXX系列的操作类就行了。行和列的角标都是从0开始的,第0行是 标题行,读取的时候注意。

该方法是利用流的方式进行的操作,如果数据量超级大,估计会导致内存溢出,要进行它法优化,一般的场景可以应付。

个人笔记,整个例子包含了读写和更改单元格的简单操作。

public void updateExcel(){

  

 try {
File file=new File("D:\\模板.xlsx");
       //读取文件的输入流
FileInputStream ism=new FileInputStream(file);
//根据流得到Workbook,
XSSFWorkbook book=new XSSFWorkbook(ism);
       //得到表
XSSFSheet sheet= book.getSheet("Sheet1");
       //表中所有的记录()
int lastRowNum = sheet.getLastRowNum();
System.out.print("文件创建成功,共有"+lastRowNum+"数据");
for(int k=1;k<=lastRowNum;k++)
            {
         //得到行
XSSFRow xssfrow = sheet.getRow(k);
            //获取单元格的内容
                   //String City = xssfrow.getCell((short) 0).getStringCellValue();
                   //获取第10列的单元格对象
if(xssfrow.getCell((short) 9)==null){
             //创建单元格并且设置值
xssfrow.createCell(9).setCellValue(9.1);
}else{
              //给单元格设置值
xssfrow.getCell((short) 9).setCellValue("9.1");
}
}
        //输出文件的流
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
          //将更改保存到Excel中
book.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

原文地址:https://www.cnblogs.com/feixian/p/5960181.html