remington_young 发表于 2016-12-31 10:43:15

利用Apache POI操纵Excel

用python时找不到合适的模块来操作(读入,然后更新某些项目,然后保存)复杂的Excel(试过python-excel,读取时有警告,部分信息丢失),就转过来使用Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class PoiExcel {
public static void main(String[] args) throws IOException {
InputStream myxls = new FileInputStream("D:\\1.xls");
HSSFWorkbook wb = new HSSFWorkbook(myxls);
HSSFCell cell = wb.getSheet("Sheet1").getRow(16).getCell(2);
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
System.out.println("单元格是字符串,值是: " + cell.getStringCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
System.out.println("单元格是日期,值是: " + cell.getDateCellValue());
} else {
System.out.println("单元格是数字,值是: " + cell.getNumericCellValue());
}
} else {
System.out.println("单元格的值不是字符串或数值。");
}
cell.setCellValue(1);
FileOutputStream fileOut = new FileOutputStream(
"D:\\2.xls");
wb.write(fileOut);
fileOut.close();
}
}

参考:POI读写Excel文件(转),Apache POI
页: [1]
查看完整版本: 利用Apache POI操纵Excel