📄 excelutil.java
字号:
package com.pengjj.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
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;
/**
* <p>Title: excel操作类</p>
* <p>Description: excel操作的各种方法:读取,写入</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: digitalchina</p>
* <p>FileName: ExcelUtil.java</p>
* @author pengjja Sep 21, 2006
* @version 1.0
*/
public class ExcelUtil extends PengjjLog{
/**
* @param args
*/
public static void main(String[] args) {
ExcelUtil excelUtil = new ExcelUtil();
String fileName = "e:/exceltest.xls";
excelUtil.getExcel(fileName);
}
/**
* 将excel文件中的内容保存到ArrayList中
* @param fileName 文件名称
* @return ArrayList
*/
public ArrayList getExcel(String fileName){
FileInputStream fileIn = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
try {
fileIn = new FileInputStream(fileName);
fs = new POIFSFileSystem(fileIn);
wb = new HSSFWorkbook(fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("文件读取出错,文件可能不存在,the filename is--"+fileName);
log.error("FileInputStream error is---"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
log.error("文件读取出错,文件可能不存在,the filename is--"+fileName);
log.error("POIFSFileSystem or HSSFWorkbook error is---"+e.getMessage());
}
//读取excel文件中的第几个sheet
//PENGJJ_TODO 默认读取底一个sheet文件
HSSFSheet sheet = wb.getSheetAt(0);
ArrayList listRow = new ArrayList();
listRow = this.getCell(sheet);
System.out.println(listRow);
return listRow;
}
/**
* 得到sheet中所有单元格的值:每一行放入一个map中,所有行放入一个list中。
* @param sheet sheet
* @return ArrayList [{0=valueCell00,1=valueCell01,2=valueCell02},
* {0=valueCell10,1=valueCell11,2=valueCell12}]
*/
public ArrayList getCell(HSSFSheet sheet){
//最后一行的位置
int iLastRow = sheet.getLastRowNum();
//最后一列的位置
int iLastCell = 0;
HSSFRow row = null;
HSSFCell cell = null;
String sValueCell = "";
HashMap mapCell = new HashMap();
ArrayList listRow = new ArrayList();
for(int i=0;i<=iLastRow;i++){
mapCell = new HashMap();
row = sheet.getRow(i);
if(row!=null){
iLastCell = row.getLastCellNum();
System.out.println("i---"+i);
for(int j=0;j<=iLastCell;j++){
System.out.println("j---"+j);
cell = row.getCell((short)j);
if(cell!=null){
sValueCell = cell.getStringCellValue();
System.out.println("--"+i+j+"----"+sValueCell);
mapCell.put(""+j,sValueCell);
}
}
listRow.add(i,mapCell);
}
}
return listRow;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -