用Java巧妙的解析Excel中的POI

用Java巧妙的解析Excel中的POI
相信各位小夥伴們,在做Java開發的時候,有時候會需要你用Java語言去解析Excel中的POI,這個時候肯定很多小夥伴們會懵逼,那麼究竟是怎麼實現的呢?本文就這個問題做了一個詳細解析。

引入依賴:
用Java巧妙的解析Excel中的POI
解析代碼:
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.itjmd.com/news/show-5367.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章