读取excel表格的内容并输出打印
1、这里用到的是xxx.xlsx的excel表,如果用.xls的旧版excel表可能会报错,需要自己调整代码
(简单的测试,取出内容根据业务自行处理)
public static void main(String[] args) throws Exception { File file = new File("D:\\test001\\qhData.xlsx"); FileInputStream inputStream = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(inputStream); XSSFSheet sheet = wb.getSheetAt(0); //读取excel的第一行 XSSFRow row1 = sheet.getRow(0); for(int i = 0; i < row1.getLastCellNum(); i++){ //循环打印(此行)的每一列内容 System.out.println(row1.getCell(i)); //订单编号, ORDER_NO, LOWER(B1) } }
2、优化升级版,传入excel文件的地址,取出里面每行,每列的数据
//读取解析EXCEL private void readExcelData(String excelPatah) { // 读取解析EXCEL InputStream inputstream; try { inputstream = new FileInputStream(excelPatah); Workbook book = null; if (!(inputstream.markSupported())) { inputstream = new PushbackInputStream(inputstream, 8); } if (POIFSFileSystem.hasPOIFSHeader(inputstream)) { book = new HSSFWorkbook(inputstream); } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) { book = new XSSFWorkbook(OPCPackage.open(inputstream)); } // 获取sheet 页数据 Sheet sheet = book.getSheetAt(0); //读取excel的第一行 // Row row1 = sheet.getRow(0); // 获取行数 int rowCount = sheet.getPhysicalNumberOfRows(); for(int i = 0; i < rowCount; i++) { //循环每一行=========================== Row row = sheet.getRow(i); if(row != null) { String sql = row.getCell(0).toString(); //第一行:sql语句 String versions = row.getCell(1).toString(); //第二行:版本号 String remark = row.getCell(2).toString(); //第三行:备注 //第一行的每一列数据打印 // for(int j = 0; j < row1.getLastCellNum(); j++){ // //循环打印(此行)的每一列内容 // System.out.println(row1.getCell(j)); // // // int r = systemService.executeSql(""); //执行sql语句 // } } } // 移动文件 // Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING); // System.out.println("file move success"); inputstream.close();//关闭流 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
。