引入依赖:
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>4.0.1</version>
- </dependency>
解析代码:
- public static void main(String[] args) {
- // [读取] ------------------------------------------------------------
- // 从 template.xls 文件中读取数据, 并保存到 ArrayList<Area> 中后打印输出.
- ArrayList<Area> list = new ArrayList<Area>();
- try {
- // 1, 获取文件输入流
- InputStream inputStream = new FileInputStream("/Users/hrvy/temp/template.xls");
- // 2, 获取 Excel 工作簿对象
- HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
- // 3, 得到 Excel 工作表对象
- HSSFSheet sheetAt = workbook.getSheetAt(0);
- // 4, 循环读取表格数据
- for (Row row : sheetAt) {
- // 首行 (即表头) 不读取
- if (row.getRowNum() == 0) {
- continue;
- }
- // 读取当前行中单元格数据, 索引从 0 开始
- String country = row.getCell(0).getStringCellValue();
- String province = row.getCell(1).getStringCellValue();
- String city = row.getCell(2).getStringCellValue();
- Area area = new Area();
- area.setCountry(country);
- area.setProvince(province);
- area.setCity(city);
- list.add(area);
- }
- System.out.println(list.toString());
- // 5, 关闭流
- workbook.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // [写出] ------------------------------------------------------------
- // 新建一个 template_copy.xls 文件, 并将 ArrayList<Area> 中的数据写入 template_copy.xls 文件
- // 1. 在内存中创建一个 Excel 文件
- HSSFWorkbook workbook = new HSSFWorkbook();
- // 2. 创建工作簿
- HSSFSheet sheet = workbook.createSheet();
- // 3. 创建标题行
- HSSFRow titlerRow = sheet.createRow(0);
- titlerRow.createCell(0).setCellValue("国家 copy");
- titlerRow.createCell(1).setCellValue("省份 copy");
- titlerRow.createCell(2).setCellValue("城市 copy");
- // 4. 遍历数据, 创建数据行
- for (Area area : list) {
- // 获取最后一行的行号
- int lastRowNum = sheet.getLastRowNum();
- // 添加新行
- HSSFRow dataRow = sheet.createRow(lastRowNum + 1);
- dataRow.createCell(0).setCellValue(area.getCountry());
- dataRow.createCell(1).setCellValue(area.getProvince());
- dataRow.createCell(2).setCellValue(area.getCity());
- }
- // 5. 创建文件名
- String fileName = "template_copy.xls";
- // 6. 获取输出流对象
- OutputStream outputStream;
- try {
- outputStream = new FileOutputStream("/Users/hrvy/temp/" + fileName);
- // 7. 写出文件, 关闭流
- workbook.write(outputStream);
- workbook.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
参照:
https://www.cnblogs.com/gdwkong/p/8669220.html
来源: http://www.bubuko.com/infodetail-2928256.html