java poi 读取excel相关问题
Published by admin on 07月 23, 2011
在项目中需要自动生成EXCEL表,思路如下:先定制一模版,然后读取模版填充数据,代码大致如下:
package cn.bidlink.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
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;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class readxls {
private static final int CELL_TYPE_NUMERIC = 0;
static String filename = “test.xls”; // 要读取的excel表的文件名称
static String c0 = null; // 单元格的内容
static String c1 = null;
static String c2 = null;
// static String c3=null;
public static void main(String[] args) throws FileNotFoundException, IOException, NullPointerException{
POIFSFileSystem file =new POIFSFileSystem(new FileInputStream(filename)); // 打开输入流
HSSFWorkbook book = new HSSFWorkbook(file); //
HSSFSheet sheet1 = book.getSheetAt(0); // 读取sheet1(book.getSheetAt(0)这里的0表示1!)
int total = sheet1.getLastRowNum(); // 读取该表的总行数
System.out.println(”loading…”);
System.out.println(”共读到数据” + total + “条”);
try{
for(int i = 0 ;i<=total;i++){
HSSFRow rows = sheet1.getRow(i); // 读取sheet1中的第i行
HSSFCell cell0 = rows.getCell((short)0); // 读取出第i行的第一列
HSSFCell cell1 = rows.getCell((short)1);
HSSFCell cell2 = rows.getCell((short)2);
// HSSFCell cell3 = rows.getCell((short)3);
// if(cell0.getCellType()==CELL_TYPE_NUMERIC || cell1.getCellType()==CELL_TYPE_NUMERIC || cell2.getCellType()==CELL_TYPE_NUMERIC){
// // 判断cell是否为数字
//
// }
c0 = cell0.getStringCellValue(); // 获取单元格的字符(内容)
c1 = cell1.getStringCellValue().trim();
c2 = cell2.getStringCellValue().trim();
// c3 = cell3.getStringCellValue();
System.out.println(c0+” | “+c1+” | “+c2);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Pages: 1 2

Add A Comment