1. 程式人生 > >Java解析Excel之POI(一)

Java解析Excel之POI(一)

lose temp () rgs data rownum 行號 新建 pla

引入依賴:

<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

Java解析Excel之POI(一)