最近做Excel导入
有两个方法:JXL 和POI
各有问题:JXL 导入:文件中有宏就报错,找不到解决方法。
POI导入:文件太大造成内存溢出。
先说问题 :Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric formula cell
这个问题是因为那一单元格使用了 “求和函数”,内容不是文本。
package cmcc.gz.platform.emss.purchase;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class XlsMain {
public static void main( String[] args) throws IOException {
XlsMain xlsMain = new XlsMain();
xlsMain.readXls();
}
private void readXls() throws IOException{
InputStream is = new FileInputStream( "F:\\导入模板V1.1.xls");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook( is);
// 循环工作表Sheet
for(int numSheet = 2; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++){
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt( numSheet);
if(hssfSheet == null){
continue;
}
// 循环行Row
for(int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++){
HSSFRow hssfRow = hssfSheet.getRow( rowNum);
if(hssfRow == null){
continue;
}
// 循环列Cell
for(int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++){
HSSFCell hssfCell = hssfRow.getCell( cellNum);
if(hssfCell == null){
continue;
}
if(hssfRow.getCell(9)!=null){//处理函数单元格问题,先将单元格内容转为String
hssfRow.getCell(9).setCellType(hssfCell.CELL_TYPE_STRING);
}
System.out.print("" + getValue( hssfCell));
}
System.out.println(" >>>");
}
}
}
@SuppressWarnings("static-access")
private String getValue(HSSFCell hssfCell){
if(hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN){
return String.valueOf( hssfCell.getBooleanCellValue());
}else if(hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC){
return String.valueOf( hssfCell.getNumericCellValue());
}else if (hssfCell.getCellType() ==hssfCell.CELL_TYPE_STRING){
return String.valueOf(hssfCell.getStringCellValue());
}else{
return String.valueOf( hssfCell.getStringCellValue());
}
}
}