1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
package site.sixteen.demoutils;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*; import java.util.Iterator;
public class {
public static void writeToExcel(Object[][] data, String fileName) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("A班"); int rowNum = 0; for (Object[] list : data) { Row row = sheet.createRow(rowNum++); int colNum = 0; for (Object value : list) { Cell cell = row.createCell(colNum++); if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Boolean) { cell.setCellValue((boolean) value); } else { cell.setCellValue(String.valueOf(value)); } } }
try (FileOutputStream outputStream = new FileOutputStream(fileName)) { workbook.write(outputStream); } }
public static void readExcel(File file) throws IOException { FileInputStream excelFile = new FileInputStream(file); Workbook workbook = new XSSFWorkbook(excelFile); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (cell.getCellTypeEnum() == CellType.STRING) { System.out.print(cell.getStringCellValue() + "t"); } else if (cell.getCellTypeEnum() == CellType.NUMERIC) { System.out.print(cell.getNumericCellValue() + "t"); } else if(cell.getCellTypeEnum() == CellType.BOOLEAN){ System.out.print(cell.getBooleanCellValue() + "t"); } else { System.out.print(cell.getStringCellValue() + "t"); } } System.out.println(); } }
public static void main(String[] args) { Object[][] datas = { {"编号", "名字", "年龄", "性别"}, {"001", "Tom", 18, true}, {"002", "Jac", 10, true}, {"003", "Oct", 24, true}, {"004", "Lil", 21, false}, }; String fileName = "/tmp/demo-write.xlsx"; try { writeToExcel(datas, fileName); } catch (IOException e) { e.printStackTrace(); } try { readExcel(new File(fileName)); } catch (IOException e) { e.printStackTrace(); } }
}
|