java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

首先,引入所需的jar包:


如果是maven管理项目的jar包,只需在pom.xml中加上:

[html]  view plain  copy
  1. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->  
  2. <dependency>  
  3.     <groupId>org.apache.poi</groupId>  
  4.     <artifactId>poi</artifactId>  
  5.     <version>3.14</version>  
  6. </dependency>  
  7. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->  
  8. <dependency>  
  9.     <groupId>org.apache.poi</groupId>  
  10.     <artifactId>poi-ooxml</artifactId>  
  11.     <version>3.14</version>  
  12. </dependency>  

POIUtil工具类的代码:

[java]  view plain  copy
  1. package com.cn.util;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11. import org.apache.poi.ss.usermodel.Cell;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16. import org.springframework.web.multipart.MultipartFile;  
  17. /** 
  18.  * excel读写工具类 
  19.  * @author sun.kai 
  20.  * 2016年8月21日 
  21.  */  
  22. public class POIUtil {  
  23.     private static Logger logger  = Logger.getLogger(POIUtil.class);  
  24.     private final static String xls = "xls";  
  25.     private final static String xlsx = "xlsx";  
  26.       
  27.     /** 
  28.      * 读入excel文件,解析后返回 
  29.      * @param file 
  30.      * @throws IOException  
  31.      */  
  32.     public static List<String[]> readExcel(MultipartFile file) throws IOException{  
  33.         //检查文件  
  34.         checkFile(file);  
  35.         //获得Workbook工作薄对象  
  36.         Workbook workbook = getWorkBook(file);  
  37.         //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回  
  38.         List<String[]> list = new ArrayList<String[]>();  
  39.         if(workbook != null){  
  40.             for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
  41.                 //获得当前sheet工作表  
  42.                 Sheet sheet = workbook.getSheetAt(sheetNum);  
  43.                 if(sheet == null){  
  44.                     continue;  
  45.                 }  
  46.                 //获得当前sheet的开始行  
  47.                 int firstRowNum  = sheet.getFirstRowNum();  
  48.                 //获得当前sheet的结束行  
  49.                 int lastRowNum = sheet.getLastRowNum();  
  50.                 //循环除了第一行的所有行  
  51.                 for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){  
  52.                     //获得当前行  
  53.                     Row row = sheet.getRow(rowNum);  
  54.                     if(row == null){  
  55.                         continue;  
  56.                     }  
  57.                     //获得当前行的开始列  
  58.                     int firstCellNum = row.getFirstCellNum();  
  59.                     //获得当前行的列数  
  60.                     int lastCellNum = row.getPhysicalNumberOfCells();  
  61.                     String[] cells = new String[row.getPhysicalNumberOfCells()];  
  62.                     //循环当前行  
  63.                     for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
  64.                         Cell cell = row.getCell(cellNum);  
  65.                         cells[cellNum] = getCellValue(cell);  
  66.                     }  
  67.                     list.add(cells);  
  68.                 }  
  69.             }  
  70.             workbook.close();  
  71.         }  
  72.         return list;  
  73.     }  
  74.     public static void checkFile(MultipartFile file) throws IOException{  
  75.         //判断文件是否存在  
  76.         if(null == file){  
  77.             logger.error("文件不存在!");  
  78.             throw new FileNotFoundException("文件不存在!");  
  79.         }  
  80.         //获得文件名  
  81.         String fileName = file.getOriginalFilename();  
  82.         //判断文件是否是excel文件  
  83.         if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){  
  84.             logger.error(fileName + "不是excel文件");  
  85.             throw new IOException(fileName + "不是excel文件");  
  86.         }  
  87.     }  
  88.     public static Workbook getWorkBook(MultipartFile file) {  
  89.         //获得文件名  
  90.         String fileName = file.getOriginalFilename();  
  91.         //创建Workbook工作薄对象,表示整个excel  
  92.         Workbook workbook = null;  
  93.         try {  
  94.             //获取excel文件的io流  
  95.             InputStream is = file.getInputStream();  
  96.             //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象  
  97.             if(fileName.endsWith(xls)){  
  98.                 //2003  
  99.                 workbook = new HSSFWorkbook(is);  
  100.             }else if(fileName.endsWith(xlsx)){  
  101.                 //2007  
  102.                 workbook = new XSSFWorkbook(is);  
  103.             }  
  104.         } catch (IOException e) {  
  105.             logger.info(e.getMessage());  
  106.         }  
  107.         return workbook;  
  108.     }  
  109.     public static String getCellValue(Cell cell){  
  110.         String cellValue = "";  
  111.         if(cell == null){  
  112.             return cellValue;  
  113.         }  
  114.         //把数字当成String来读,避免出现1读成1.0的情况  
  115.         if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){  
  116.             cell.setCellType(Cell.CELL_TYPE_STRING);  
  117.         }  
  118.         //判断数据的类型  
  119.         switch (cell.getCellType()){  
  120.             case Cell.CELL_TYPE_NUMERIC: //数字  
  121.                 cellValue = String.valueOf(cell.getNumericCellValue());  
  122.                 break;  
  123.             case Cell.CELL_TYPE_STRING: //字符串  
  124.                 cellValue = String.valueOf(cell.getStringCellValue());  
  125.                 break;  
  126.             case Cell.CELL_TYPE_BOOLEAN: //Boolean  
  127.                 cellValue = String.valueOf(cell.getBooleanCellValue());  
  128.                 break;  
  129.             case Cell.CELL_TYPE_FORMULA: //公式  
  130.                 cellValue = String.valueOf(cell.getCellFormula());  
  131.                 break;  
  132.             case Cell.CELL_TYPE_BLANK: //空值   
  133.                 cellValue = "";  
  134.                 break;  
  135.             case Cell.CELL_TYPE_ERROR: //故障  
  136.                 cellValue = "非法字符";  
  137.                 break;  
  138.             default:  
  139.                 cellValue = "未知类型";  
  140.                 break;  
  141.         }  
  142.         return cellValue;  
  143.     }  
  144. }  

POIUtil.readExcel方法读取excel文件后,把一行中的值按先后顺序组成一个数组,所有的行作为一个集合返回。我们可以在代码中循环这个集合,把数组赋值到实体类对象中。

我在前台用form表单提交file文件,因为用的SpringMVC框架,后台用MultipartFile接收,代码如下:

[java]  view plain  copy
  1. /** 
  2.  * 读取excel文件中的用户信息,保存在数据库中 
  3.  * @param excelFile 
  4.  */  
  5. @RequestMapping("/readExcel")  
  6. public void readExcel(@RequestParam(value = "excelFile") MultipartFile excelFile,HttpServletRequest req,HttpServletResponse resp){  
  7.     Map<String, Object> param = new HashMap<String, Object>();  
  8.     List<User> allUsers = new ArrayList<User>();  
  9.     try {  
  10.         List<String[]> userList = POIUtil.readExcel(excelFile);  
  11.         for(int i = 0;i<userList.size();i++){  
  12.           String[] users = userList.get(i);  
  13.           User user = new User();  
  14.           user.setUserName(users[0]);  
  15.           user.setPassword(users[1]);  
  16.           user.setAge(Integer.parseInt(users[2]));  
  17.           allUsers.add(user);  
  18.          }  
  19.        } catch (IOException e) {  
  20.         logger.info("读取excel文件失败", e);  
  21.        }  
  22.      param.put("allUsers", allUsers);  
  23.      this.userService.insertUsers(param);  
  24. }  

调用的service层方法就不贴代码了,下面就是往数据库插入数据了。

excel文件内容:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 Excel 转 PDF 兼容 xlsxlsx 格式的方法与上面的示例代码类似,需要使用 POI 读取 Excel 文件,然后根据不同的格式进行不同的处理。 对于自动转行,可以在写入 PDF 的时候,使用 PdfPTable 和 PdfPCell 对象实现。具体的实现方法如下: ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; public class ExcelToPdf { public static void main(String[] args) throws IOException, DocumentException { String excelPath = "path/to/excel/file.xlsx"; String pdfPath = "path/to/pdf/file.pdf"; // 读取 Excel 文件 Workbook workbook = getWorkbook(excelPath); // 创建 PDF 文件 Document document = new Document(PageSize.A4); PdfWriter.getInstance(document, new FileOutputStream(pdfPath)); document.open(); // 遍历 Excel 中的每个 Sheet for (int i = 0; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); int rowCount = sheet.getPhysicalNumberOfRows(); // 创建 PdfPTable 对象 PdfPTable table = new PdfPTable(sheet.getRow(0).getPhysicalNumberOfCells()); table.setWidthPercentage(100); // 遍历 Sheet 中的每一行 for (int j = 0; j < rowCount; j++) { Row row = sheet.getRow(j); if (row != null) { // 遍历每一列,将单元格内容添加到 PdfPCell 中 for (int k = 0; k < row.getPhysicalNumberOfCells(); k++) { Cell cell = row.getCell(k); if (cell != null) { PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph(cell.toString())); table.addCell(pdfPCell); } } } } // 将 PdfPTable 添加到 PDF 中 document.add(table); } // 关闭 Workbook 和 Document 对象,保存 PDF 文件 workbook.close(); document.close(); } private static Workbook getWorkbook(String excelPath) throws IOException { Workbook workbook = null; if (excelPath.endsWith(".xls")) { workbook = new HSSFWorkbook(excelPath); } else if (excelPath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(excelPath); } return workbook; } } ``` 在上面的代码中,我们使用 getWorkbook 方法来获取 Excel 文件对应的 Workbook 对象。在遍历 Sheet 中的每一行和每一列时,我们将单元格内容添加到 PdfPCell 中,并将 PdfPCell 添加到 PdfPTable 中。由于 PdfPTable 对象会自动将内容转行,因此我们不需要手动进行转行的处理。最后,我们将 PdfPTable 对象添加到 PDF 文件中即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值