如何利用poi技术操作Excel表格?

poi技术实现excel的操作

poi技术简介

Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件

poi依赖

 <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version>
  </dependency>

poi结构

  • HSSF - 提供读写Microsoft Excel XLS格式档案的功能
  • XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能
  • HWPF - 提供读写Microsoft Word DOC格式档案的功能
  • HSLF - 提供读写Microsoft PowerPoint格式档案的功能
  • HDGF - 提供读Microsoft Visio格式档案的功能
  • HPBF - 提供读Microsoft Publisher格式档案的功能
  • HSMF - 提供读Microsoft Outlook格式档案的功能

从Excel表中读文件

创建readExcel类

public class ReadExcel {
    
    

    public void ReadExcel() throws Exception {
    
    
        // 创建输入流对象,把指定的excel文件放入流中
        File file = new File("D:/develop/IDEA/javaUp/poi_Excel/person.xls");
        FileInputStream fis =  new FileInputStream(file);
        // 创建一个HSSFWorkbook 对象  xls文档对象
        HSSFWorkbook workbook = new HSSFWorkbook(fis);
        // 找到指定的工作簿对象
        HSSFSheet sheet = workbook.getSheetAt(0);
        // 找到最后一行的行号,用作循环
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <lastRowNum ; i++) {
    
    
            // 获取指定的行对象
            HSSFRow row = sheet.getRow(i);
            int id = (int) row.getCell(0).getNumericCellValue();
            String name = row.getCell(1).getStringCellValue();
            String gender = row.getCell(2).getStringCellValue();
            int age = (int) row.getCell(3).getNumericCellValue();
            Date birthday = row.getCell(4).getDateCellValue();
            System.out.println(id+"\t"+name+"\t"+gender+"\t"+age+"\t"+birthday);
        }
        // 关闭资源
        workbook.close();
        fis.close();

    }
}

调用测试 获取成功

@org.junit.Test
public void test() throws Exception {
    
    
    ReadExcel readExcel = new ReadExcel();
    readExcel.ReadExcel();
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KlkFJLqM-1657031520074)(E:\Java资料\笔记整理\JavaUp\笔记整理\poi技术实现excel的操作.assets\image-20220628151621260.png)]

往Excel表中写文件

创建writeExcel类

public class WriteExcel {
    
    

    public void writeExcel() throws Exception{
    
    

        // 创建HSSFWorkbook对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作簿对象
        HSSFSheet sheet = workbook.createSheet("学生表");
        // 创建标题行
        HSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("姓名");
        row0.createCell(1).setCellValue("年龄");
        row0.createCell(2).setCellValue("住址");
        row0.createCell(3).setCellValue("爱好");

        // 创建内容行
        HSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("张三");
        row1.createCell(1).setCellValue(23);
        row1.createCell(2).setCellValue("上海");
        row1.createCell(3).setCellValue("篮球");

        HSSFRow row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("李四");
        row2.createCell(1).setCellValue(25);
        row2.createCell(2).setCellValue("北京");
        row2.createCell(3).setCellValue("足球");

        // 写入数据
        workbook.write(new FileOutputStream("D:/develop/IDEA/javaUp/poi_Excel/student.xls"));

        // 关闭资源
        workbook.close();
    }
}

调用测试

@org.junit.Test
public void test1() throws Exception {
    
    
    WriteExcel writeExcel = new WriteExcel();
    writeExcel.writeExcel();
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jr5eJ1Ne-1657031520075)(E:\Java资料\笔记整理\JavaUp\笔记整理\poi技术实现excel的操作.assets\image-20220628153124736.png)]

工具类

package com.chenshuang.util;

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;
    }
}

案例

往服务器的文件中些信息

    // 创建输入流对象,把指定的excel文件放入流中--【文件再服务器的本地位置】
    File file = new File("D:\\develop\\IDEA\\javaUp\\pro\\chenshuangpe_parent\\chenshuangpe_controller\\src\\main\\resources\\static\\template\\report_template.xlsx");
    FileInputStream fis = new FileInputStream(file);
    // 创建一个XSSFWorkbook 对象  xlsx文档对象
    XSSFWorkbook workbook = new XSSFWorkbook(fis);

    XSSFSheet sheet = workbook.getSheet("data");
    XSSFRow row2 = sheet.getRow(2);
    row2.getCell(5).setCellValue(nowDate);
    XSSFRow row4 = sheet.getRow(4);
    row4.getCell(5).setCellValue(todayNewMember);
    row4.getCell(7).setCellValue(totalMember);
    XSSFRow row5 = sheet.getRow(5);
    row5.getCell(5).setCellValue(thisWeekNewMember);
    row5.getCell(7).setCellValue(thisMonthNewMember);
    XSSFRow row7 = sheet.getRow(7);
    row7.getCell(5).setCellValue(todayOrderNumber);
    row7.getCell(7).setCellValue(todayVisitsNumber);
    XSSFRow row8 = sheet.getRow(8);
    row8.getCell(5).setCellValue(thisWeekOrderNumber);
    row8.getCell(7).setCellValue(thisWeekVisitsNumber);
    XSSFRow row9 = sheet.getRow(9);
    row9.getCell(5).setCellValue(thisMonthOrderNumber);
    row9.getCell(7).setCellValue(thisMonthVisitsNumber);

    // -----------------写入热门套餐

    for (int i = 0; i < hotSetmeal.size(); i++) {
    
    
        Map map = hotSetmeal.get(i);
        String name = (String) map.get("name");
        String code = (String) map.get("code");
        
        XSSFRow rowS1 = sheet.getRow(12 + i);
        rowS1.getCell(4).setCellValue(name);
        rowS1.getCell(5).setCellValue(map.get("setmeal_count").toString());
        rowS1.getCell(6).setCellValue(code);
        rowS1.getCell(7).setCellValue(map.get("proportion").toString());
    }
    // 写入文件
    workbook.write(new FileOutputStream(file));
    workbook.close();
    fis.close();

从服务器下载

前端

methods:{
    exportExcel(){
        window.location.href = '/report/exportBusinessReport';
    }
}

后端业务

//        ------------------------- 写数据  ----------------------
        {
    
    
            // 创建输入流对象,把指定的excel文件放入流中
            File file = new File("D:\\develop\\IDEA\\javaUp\\pro\\chenshuangpe_parent\\chenshuangpe_controller\\src\\main\\resources\\static\\template\\report_template.xlsx");
            FileInputStream fis = new FileInputStream(file);
            // 创建一个XSSFWorkbook 对象  xlsx文档对象
            XSSFWorkbook workbook = new XSSFWorkbook(fis);

            XSSFSheet sheet = workbook.getSheet("data");
            XSSFRow row2 = sheet.getRow(2);
            row2.getCell(5).setCellValue(nowDate);
            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(5).setCellValue(todayNewMember);
            row4.getCell(7).setCellValue(totalMember);
            XSSFRow row5 = sheet.getRow(5);
            row5.getCell(5).setCellValue(thisWeekNewMember);
            row5.getCell(7).setCellValue(thisMonthNewMember);
            XSSFRow row7 = sheet.getRow(7);
            row7.getCell(5).setCellValue(todayOrderNumber);
            row7.getCell(7).setCellValue(todayVisitsNumber);
            XSSFRow row8 = sheet.getRow(8);
            row8.getCell(5).setCellValue(thisWeekOrderNumber);
            row8.getCell(7).setCellValue(thisWeekVisitsNumber);
            XSSFRow row9 = sheet.getRow(9);
            row9.getCell(5).setCellValue(thisMonthOrderNumber);
            row9.getCell(7).setCellValue(thisMonthVisitsNumber);

            // -----------------写入热门套餐

            for (int i = 0; i < hotSetmeal.size(); i++) {
    
    
                Map map = hotSetmeal.get(i);
                String name = (String) map.get("name");
                String code = (String) map.get("code");

                XSSFRow rowS1 = sheet.getRow(12 + i);
                rowS1.getCell(4).setCellValue(name);
                rowS1.getCell(5).setCellValue(map.get("setmeal_count").toString());
                rowS1.getCell(6).setCellValue(code);
                rowS1.getCell(7).setCellValue(map.get("proportion").toString());
            }
            // 写入文件
            workbook.write(new FileOutputStream(file));
            workbook.close();
            fis.close();
        }
name);
                rowS1.getCell(5).setCellValue(map.get("setmeal_count").toString());
                rowS1.getCell(6).setCellValue(code);
                rowS1.getCell(7).setCellValue(map.get("proportion").toString());
            }
            // 写入文件
            workbook.write(new FileOutputStream(file));
            workbook.close();
            fis.close();
        }

猜你喜欢

转载自blog.csdn.net/PIKapikaaaa/article/details/125629545