package com.zving.demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelStudy { public static void main(String[] args) { exportExcel(); readExcel(); } /* * 导出Excel表格 */ public static void exportExcel() { String[] title = { "id", "name", "sex" };// 表头 // 创建Excel表格 @SuppressWarnings("resource") HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作表sheet HSSFSheet sheet = workbook.createSheet(); // 创建第一行 HSSFRow row = sheet.createRow(0); // 定义单元格 HSSFCell cell = null; // 插入表头数据(第一行) for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); } // 插入单元格数据(第二行开始) for (int i = 1; i < 10; i++) { HSSFRow nextRow = sheet.createRow(i); HSSFCell cell2 = nextRow.createCell(0); cell2.setCellValue("a" + i); cell2 = nextRow.createCell(1); cell2.setCellValue("user" + i); cell2 = nextRow.createCell(2); cell2.setCellValue("男"); } // 创建Excel文件 File file = new File("C:\\Users\\Clover\\Desktop\\abc.xls"); try { file.createNewFile(); FileOutputStream fos = FileUtils.openOutputStream(file); workbook.write(fos); fos.close(); } catch (Exception e) { e.printStackTrace(); } } /* * 解析Excel表格 */ public static void readExcel() { File file = new File("C:\\Users\\Clover\\Desktop\\abc.xls"); try { // 读取文件内容 @SuppressWarnings("resource") HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file)); // 读取第一条工作表sheet HSSFSheet sheet = workbook.getSheetAt(0); int firstRow = 0; // 第一行 int lastRow = sheet.getLastRowNum(); // 最后一行 for (int i = firstRow; i < lastRow; i++) { HSSFRow row = sheet.getRow(i); // 循环获取每一行 int lastCell = row.getLastCellNum(); // 获取每一行的单元格数量 for (int j = 0; j < lastCell; j++) { HSSFCell cell = row.getCell(j); // 循环获取每一单元格 String value = cell.getStringCellValue();// 获取每一单元格的数据 System.out.print(value + " "); } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } } }
O(∩_∩)O开心就好O(∩_∩)O