多说两句:表格的导入导出,是比较常见的系统操作,一般涉及数据批量导入导出时会用到,以前遇到过的业务场景有批量添加会员信息,数据迁移等。实现工具,Apache的poi最为常见。实现简单,博客简单一记。
实现工具:Apache POI - the Java API for Microsoft Documents
官网:https://poi.apache.org/
-
HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
-
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
-
HWPF - 提供读写Microsoft Word DOC97格式档案的功能。
-
XWPF - 提供读写Microsoft Word DOC2003格式档案的功能。
-
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
-
HDGF - 提供读Microsoft Visio格式档案的功能。
-
HPBF - 提供读Microsoft Publisher格式档案的功能。
-
HSMF - 提供读Microsoft Outlook格式档案的功能。
下面的java程序是利用HSSF,实现excel导入功能:
maven坐标:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
根据自己需要,我用的版本有点旧,现在版本已到3.17.
表格准备:在D盘的excel文件夹下新建“联系人.xls”表格。
实现代码:
public static void main(String[] args) {
try {
//读文件
InputStream input = new FileInputStream("D:/example/联系人信息.xls");
//xssfWorkbook对应于你读到的这个表格
HSSFWorkbook xssfWorkbook = new HSSFWorkbook(input);
//一个表格可能有好多sheet,通过getSheetAt(0),拿到第一个sheet
HSSFSheet sheet = xssfWorkbook.getSheetAt(0);
if (sheet != null) {
// 0
String username = "";
// 1
String age = "";
// 2
String sex = "";
//遍历行,i = 1,从第二行开始,第一行是表头跳过。
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//row是一行数据,row.getCell(i),代表拿到这一行,第i列数据
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
Cell cell = null;
cell = row.getCell(0);
username = cell == null ? "" : cell.toString();
cell = row.getCell(1);
age = cell == null ? "" : cell.toString();
cell = row.getCell(2);
sex = cell == null ? "" : cell.toString();
System.out.println(username+" "+age+" "+sex);//张三 18 男
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
可能出现的异常: nested exception is org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. POI only supports OLE2 Office documents
原因是:
HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls
XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx
解决方案:把高版本的excel,通过另存为保存为低版本的,如:123.xlsx,另存为123.xls。可以解决上述异常。
导出:Java实现Excel表格的导入和导出(二)