利用java poi对excel表的读写操作
POI简介:
Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件。这由Apache软件基金会开发使用Java分布式设计或修改Microsoft Office文件的开源库。它包含类和方法对用户输入数据或文件到MS Office文档进行解码
核心jar包
org.apache.poi poi 3.16
读取
/** * 读取数据 */private static void readExcel() { // TODO Auto-generated method stub String path = "D://test.xlsx"; InputStream is; try { is = new FileInputStream(path); XSSFWorkbook xssfWorkbook; XSSFSheet xssfSheet; xssfWorkbook = new XSSFWorkbook(is); xssfSheet = xssfWorkbook.getSheetAt(0); //按行进行读取 for (int rowNum = 0; rowNum < xssfSheet.getLastRowNum(); rowNum++) { // 读取该行第一列 String userName = getValue(xssfSheet.getRow(rowNum).getCell(0)); //读取改行的第二列数据 String password = getValue(xssfSheet.getRow(rowNum).getCell(1)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }}@SuppressWarnings("static-access")private static String getValue(XSSFCell xssfRow) { if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) { return String.valueOf(xssfRow.getBooleanCellValue()); } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) { return String.valueOf(xssfRow.getNumericCellValue()); } else { return String.valueOf(xssfRow.getStringCellValue()); }}
写入
/** * 写入数据 */private static void writeExcel() { // TODO Auto-generated method stub // TODO Auto-generated method stub String path = "D://test.xlsx"; InputStream is; try { is = new FileInputStream(path); XSSFWorkbook xssfWorkbook; XSSFSheet xssfSheet; xssfWorkbook = new XSSFWorkbook(is); xssfSheet = xssfWorkbook.getSheetAt(0); String[] titles = { "标题1", "标题2", "标题3"}; // 在哪一行写入数据 XSSFRow titleRow = xssfSheet.getRow(0); for (int i = 0; i < titles.length; i++) {// 按标题的个数及顺序写入列 XSSFCell titleCell = titleRow.createCell(titleRow .getLastCellNum()); titleCell.setCellValue(titles[i]); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }}
感谢知行办公团队同事的帮助
- @gmail.com;
- 【安全】保密,你懂的。