java poi读取excel

njlycq 2011-08-11 02:25:22
今天遇到一个问题,用java poi读取excel
excel的格式大概如下
A1 A11
A A12
A13
A2 A21
B B1 B11
B12
B13
B14
C C1 C11
excel里面有合并单元格,比如第一列是A,B,C A占了4行,A1占了3行,A11...A13各自占一行,我现在需要读取
A+A1+A11,A+A1+A12.....每行存取一条数据到数据库中。
请高人指教。。。。。。

...全文
47 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
softroad 2011-08-11
  • 打赏
  • 举报
回复

public static Map<String, Object> readExcelFile(Sheet sheet) {
Map<String, Object> map = new LinkedHashMap<String, Object>();

if(sheet == null || sheet.getLastRowNum() == 0) {
return map;
}
else {
map.put("sheetName", sheet.getSheetName());
}

for(int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);

if(row == null || row.getLastCellNum() == 0) {
continue;
}

for(int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
Cell cell = row.getCell(cellIndex);
cell = cell == null ? row.createCell(cellIndex) : cell;
String val = "";

switch(cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
val = cell.getStringCellValue().trim();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if(HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat format =
new SimpleDateFormat("yyyy-MM-dd");
val = format.format(
new Date(cell.getDateCellValue().getTime()));
}
else {
Double d = cell.getNumericCellValue();
//DecimalFormat df = new DecimalFormat();
//df.applyPattern("0");
val = String.valueOf(d);
}

break;
}
}

if(bean.getKey() != null) {
map.put(bean.getKey(), bean);
}
}

return map;
}
softroad 2011-08-11
  • 打赏
  • 举报
回复

public static Map<String, Object> readExcel(File excel) throws Exception {
InputStream in = new FileInputStream(excel);
Workbook book = null;

try {
book = new HSSFWorkbook(in);
}
catch(OutOfMemoryError e) {
String msg = "The file " + excel.getName()
+ " data is error, please delete invalid data!";
if(log.isDebugEnabled()) {
log.debug(msg);
}

throw new Exception(msg);
}
catch(OfficeXmlFileException e) {
in = new FileInputStream(excel);
book = new XSSFWorkbook(in);
//throw new Exception(e.getMessage());
}

if(book == null || book.getNumberOfSheets() == 0) {
return null;
}

for(int sheetNum = 0; sheetNum < book.getNumberOfSheets(); sheetNum++) {
Sheet sheet = book.getSheetAt(sheetNum);

if(sheet == null || sheet.getLastRowNum() == 0) {
return null;
}

return readExcelFile(sheet);
}

return null;
}

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧