2020-11-17 09:24阅读: 692评论: 0推荐: 0

JAVA Poi工具类

  Apache POI 简介是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“可怜的模糊实现”。

  HSSF - 提供读写Microsoft Excel XLS格式档案的功能 (office97-2003版本支持,.xls)
  XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能(office 2007以后的版本支持,.xlsx)
  HWPF - 提供读写Microsoft Word DOC格式档案的功能
  HSLF - 提供读写Microsoft PowerPoint格式档案的功能
  HDGF - 提供读Microsoft Visio格式档案的功能
  HPBF - 提供读Microsoft Publisher格式档案的功能
  HSMF - 提供读Microsoft Outlook格式档案的功能

1.pom

复制代码
 <dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.14</version>
 </dependency>
 <dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.14</version>
 </dependency>
复制代码

2.工具类 适用与上传解析

复制代码
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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 org.springframework.web.multipart.MultipartFile;

public class POIUtils {
    private final static String xls = "xls";
    private final static String xlsx = "xlsx";
    private final static String DATE_FORMAT = "yyyy/MM/dd";

    /**
     * 读入excel文件,解析后返回
     *
     * @param file
     * @throws IOException
     */
    public static List<String[]> readExcel(MultipartFile file) throws IOException {
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
        List<String[]> list = new ArrayList<String[]>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
                    int lastCellNum = row.getPhysicalNumberOfCells();
                    String[] cells = new String[row.getPhysicalNumberOfCells()];
                    //循环当前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getCellValue(cell);
                    }
                    list.add(cells);
                }
            }
            workbook.close();
        }
        return list;
    }

    //校验文件是否合法
    public static void checkFile(MultipartFile file) throws IOException {
        //判断文件是否存在
        if (null == file) {
            throw new FileNotFoundException("文件不存在!");
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)) {
            throw new IOException(fileName + "不是excel文件");
        }
    }

    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象,表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (fileName.endsWith(xls)) {
                //2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith(xlsx)) {
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //如果当前单元格内容为日期类型,需要特殊处理
        String dataFormatString = cell.getCellStyle().getDataFormatString();
        if (dataFormatString.equals("m/d/yy")) {
            cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
            return cellValue;
        }
        //把数字当成String来读,避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
}
复制代码

 3.导出示例

复制代码
    @RequestMapping("/exportReport")
    public String exportBusinessReport(HttpServletResponse response){
        try {

            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager
                    .getConnection("jdbc:mysql://", "root", "root");
            //获取模本的流对象
            InputStream inputStream = DemoController.class.getResourceAsStream("/template/calgetdata.xlsx");
            //创建工作薄对象
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //获取工作表对象
            XSSFSheet sheet =  workbook.getSheetAt(0);

            int rowNum=1;
            int columnNum=4;
            int lastRowNum = sheet.getLastRowNum();
            while (lastRowNum!=rowNum) {
                //获取行
                XSSFRow row = sheet.getRow(rowNum);
                //获取单元格
                XSSFCell cell = row.getCell(columnNum);
                String aaa = POIUtils.getCellValue(cell);

                cell = row.getCell(14);
                String startYearMonth = POIUtils.getCellValue(cell);
                if ("".equals(aaa)||null==aaa){
                    break;
                }
                pstmt = conn.prepareStatement("select yearm,aaa , a , b ,c  " +
                        "from demo where aaa ='"+aaa+"'  order by IndexCalNo");
                rs = pstmt.executeQuery();
                Boolean flag=true;
                int aNum=15;
                while (rs.next()) {
                    String yearm = rs.getString("yearm");
                    String yearMonth = startYearMonth.substring(0, 4) + startYearMonth.substring(5, 7);
                    if (yearm.equals(yearMonth)){
                        flag=false;
                    }else {
                        if (!yearm.equals(yearMonth)&&flag){
                            flag=false;
                            continue;
                        }
                    }

                    cell = row.getCell(aNum);
                    String a=rs.getString("a");
                    cell.setCellValue(a);
                    int bNum=aNum+12;
                    cell = row.getCell(bNum);
                    String b=rs.getString("b");
                    cell.setCellValue(b);
                    int cNum=bNum+12;
                    cell = row.getCell(cNum);
                    String c=rs.getString("c");
                    cell.setCellValue(c);

                    aNum++;
                }
                System.out.println(rowNum+""+aaa);
                rowNum++;
            }
            Date date = new Date();
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename="+date.getTime()+"_report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
复制代码

 

本文作者:zydjjcpdszylddpll

本文链接:https://www.cnblogs.com/jyfs/p/13992533.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   zydjjcpdszylddpll  阅读(692)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起