公司需要处理一些Excel文件数据。懒,搜索了以下读取方法.
忘记出自网络上那里的了、
记录下来,以后可以学习学习,需要导入jar包 poi-3.6-20091214.jar等,所需jar包在后面下载
1、读取Excel
public class ReadExcel {
public static void main(String[]args){
ArrayList<String> columnList = new ArrayList<String>();
File file = new File("E:\\test.xls");
try {
FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in);
Sheet sheet = wb.getSheetAt(0);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
Row row = null;
Cell cell_a = null;
for (int i = firstRowNum; i <= lastRowNum; i++) {
row = sheet.getRow(i); //取得第i行
if(row!=null){
cell_a = row.getCell(4); //取得i行的第4列
if(cell_a!=null){
String cellValue = cell_a.getCellType()+"";
columnList.add(cellValue);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
2、写入Excel
public class WriteExcel {
public static void main(String[] args) {
Workbook workbook = null;
Sheet sheet = null;
try {
OutputStream out = new FileOutputStream("E:\\test.xls");
workbook = new HSSFWorkbook();
sheet = workbook.createSheet("testWrite");
Row row = null;
Cell cell = null;
for(int i=0;i<6;i++){
row = sheet.createRow(i);
for(int j = 0;j<6;j++){
cell = row.createCell(j);
sheet.setColumnWidth(j, 4500);
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
cell.setCellValue((i+j)%2==0 ? true : false);
}
}
workbook.write(out);
if(out!=null) out.flush();
if(out!=null) out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}