一、导入依赖的包【maven】
<!-- 引入poi,解析workbook视图 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- 处理excel和上面功能是一样的-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
二、写入
//第一步,创建一个workbook对应一个excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//第二部,在workbook中创建一个sheet对应excel中的sheet
HSSFSheet sheet = workbook.createSheet("用户表一");
//第三部,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制
HSSFRow row = sheet.createRow(0);
//第四步,创建单元格,设置表头
HSSFCell cell = row.createCell(0);
cell.setCellValue("用户名");
cell = row.createCell(1);
cell.setCellValue("密码");
//第五步,写入实体数据,实际应用中这些数据从数据库得到,对象封装数据,集合包对象。对象的属性值对应表的每行的值
for (int i = 0; i < 5; i++) {
HSSFRow row1 = sheet.createRow(i + 1);
//创建单元格设值
row1.createCell(0).setCellValue("张三");
row1.createCell(1).setCellValue("mima");
}
//将文件保存到指定的位置
try {
FileOutputStream fos = new FileOutputStream("/Users/**/Documents/user1.xls");
workbook.write(fos);
System.out.println("写入成功");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
三、读取【inputStream】
FtpClientService ftpClientService = new FtpClientService();
boolean b = ftpClientService.connect("/FTP/**/**/**/**", "192.168.2.11", 21, "COUNT", "PASSWORD");
InputStream inputStream = ftpClientService.readFtp("user1.xls");
//使用inputStream
Map map = new HashMap();
Workbook workbook = Workbook.getWorkbook(inputStream); //处理输入流
Sheet sheet = workbook.getSheet(0);// 获取第一个sheet
int rows = sheet.getRows(); //获取总行号
String[][] curArr = new String[rows][2]; //存放正确心细
String[][] errorArr = new String[rows * 2][4]; //存放错误信息
int curLines = 0;
int errorLines = 0;
for (int i = 1; i < rows; i++) {// 遍历行获得每行信息
String phone = sheet.getCell(0, i).getContents();// 获得第i行第1列信息
String shortNum = sheet.getCell(1, i).getContents();// 短号
StringBuffer errorMsg = new StringBuffer();
System.out.print("\n\nphone= "+phone);
System.out.print("\n\nshortNum= "+shortNum);
}