java处理excel文件的读写
简述
1、一般会将文件地址作为入参,对文件进行处理
2、将文件放到File中:File file = new File(fileName)
3、判断文件是否存在:if(!file.exists()){return null;}
4、将文件放入流中进行处理:InputStream is= new FileInputStream(file)
5、创建工作部:Workbook wb= new HSSFWorkbook(is),创建方式不一样,XSSFWorkbook
6、获取excel中的一个表格 Sheet sheet = wb.getSheetAt(0);
7、遍历表格里的数据
8、捕获异常,关闭流。
示例代码如下:
点击查看代码
public static Map<String, String> readExcel(String fileName){
Map<String, String> map = new HashMap<String, String>();
File file = new File(fileName);
if (!file.exists()) {
return null;
}
InputStream is = null;
try {
is = new FileInputStream(file);
Workbook wb = null;
if (fileName.endsWith(".xls")) {
// 2003版本
wb = new HSSFWorkbook(is);
} else if (fileName.endsWith(".xlsx")) {
// 2007版本
wb = new XSSFWorkbook(is);
} else {
throw new ExcelReadException("文件类型不正确或不是Excel文件");
}
Sheet sheet = wb.getSheetAt(0);
AddressInfo tbAddress = null;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
tbAddress = new AddressInfo();
Row rows = sheet.getRow(i);
if (rows == null) {
continue;
}
String oldAddress = rows.getCell(0).getStringCellValue() + rows.getCell(1).getStringCellValue() + rows.getCell(2).getStringCellValue();
tbAddress.setProvince(rows.getCell(4).getStringCellValue());
tbAddress.setCity(rows.getCell(5).getStringCellValue());
tbAddress.setArea(rows.getCell(6).getStringCellValue());
map.put(oldAddress.toString(), tbAddress.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return map;
}
本文来自博客园,作者:转身我便在你身后,转载请注明原文链接:https://www.cnblogs.com/jqqlf/p/17001025.html