• POI


    一、在Java工程中使用POI

      1、导入jar包

    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
         </dependency>
    </dependencies>    
    View Code

               

      2、Excel文件的结构

    Excel文件

    |
    sheet:工作表,在这个级别对列宽进行控制
    |
    row:行
    |
    cell:单元格

    3、导入一个Excel表格

    @Test
    public void testRead() throws Exception {
    //1.创建Workbook对象
    Workbook wb = WorkbookFactory.create(new File("C:\Users\Administrator\Desktop\1.xlsx"));
    //2.从Workbook对象中获取第一个sheet
    Sheet sheet = wb.getSheetAt(0);
    //3.从第一个sheet中得到第一行数据
    Row row = sheet.getRow(0);
    //4.从第一行中获取第一列数据
    Cell cell = row.getCell(0);
    System.out.println(cell.getCellType());
    System.out.println(cell.getStringCellValue());
    }
    View Code

    4、遍历一个Excel表格

    //将不同的数据类型,转换成string类型的!
    private String getCellValue(Cell c){
    String o = null;
    switch(c.getCellType()){
    case Cell.CELL_TYPE_BLANK:
    o = "";
    break;
    case Cell.CELL_TYPE_BOOLEAN:
    o = String.valueOf(c.getBooleanCellValue());
    break;
    case Cell.CELL_TYPE_FORMULA:
    o = String.valueOf(c.getCellFormula());
    break;
    case Cell.CELL_TYPE_NUMERIC:
    o = String.valueOf(c.getNumericCellValue());
    break;
    case Cell.CELL_TYPE_STRING:
    o = c.getStringCellValue();
    break;
    default:
    o = null;
    break;
    }
    return o;
    }
    View Code

       测试 

    @Test
    public void testForeachExcel() throws Exception{
    Workbook wb = WorkbookFactory.create(new File("C:\Users\Administrator\Desktop\1.xlsx"));
    Sheet sheet = wb.getSheetAt(0);
    
    Row row = null;
    //获取每一行
    for(int i = 0 ; i< sheet.getLastRowNum();i++){
    row = sheet.getRow(i);
    //对每一行的每一列遍历!
    for(int j=0;j<row.getLastCellNum();j++){
    System.out.print(getCellValue(row.getCell(j))+"======");
    }
    System.out.println();
    }
    } 
    View Code

            变1:当然上面的读取方式从POI3.8开始也是支持增强for循环读取数据的!

    @Test
    public void testForeachExcel() throws Exception{
    Workbook wb = WorkbookFactory.create(new File("C:\Users\Administrator\Desktop\1.xlsx"));
    Sheet sheet = wb.getSheetAt(0);
    //获取每一行
    for(Row row : sheet){
    for(Cell cell:row){
    System.out.print(getCellValue(cell)+"---");
    }
    System.out.println();
    }
    }
    View Code

    二、创建Excel表格

    1、创建一个空白的Excel表格 

     

    @Test
    public void testWriteExcel() throws Exception{
    Workbook wb = new HSSFWorkbook();
    FileOutputStream fos = new FileOutputStream("D:/1.xlsx");
    wb.write(fos);
    
    if(fos != null){
    fos.close();
    }
    }    
    View Code

    2、创建Excel步骤

      1)创建代表一个Excel文件的HSSFWorkbook对象

        HSSFWorkbook workbook = new HSSFWorkbook();
      2)创建代表一个工作表的HSSFSheet对象
        HSSFSheet sheet = workbook.createSheet("工作表名称");
      3)创建代表行的HSSFRow对象
        HSSFRow row = sheet.createRow(index);    //index表示行的索引,从0开始
      4)创建代表单元格的HSSFCell对象
        HSSFCell cell = row.createCell(index);           //index表示单元格的索引,从0开始
      5)将Excel文件写入到文件系统中
        ①.创建一个文件输出流对象
          FileOutputStream outputStream = new FileOutputStream("文件路径");
        ②.将文件内容写入到这个输出流
          workbook.write(outputStream);

      案例1:

    @Test
    public void test() throws Exception {
    //1.创建代表Excel文件的HSSFWorkBook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    //2.在当前Excel文件中创建工作表
    HSSFSheet sheet = workbook.createSheet();
    //3.在当前工作表中,创建行
    HSSFRow row = sheet.createRow(0);
    //4.在当前行中,创建单元格
    HSSFCell cell = row.createCell(0);
    //5.给单元格设置值
    cell.setCellValue("不要迷恋哥,哥只是个传说!");
    //6.创建输出流,写入到硬盘上!
    FileOutputStream out = new FileOutputStream("d:\text.xls");
    workbook.write(out);
    }
    View Code

        案例2:

    @Test
    public void test() throws Exception {
    //1.创建代表Excel文件的HSSFWorkBook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    //2.在当前Excel文件中创建工作表
    HSSFSheet sheet = workbook.createSheet();
    //3.在当前工作表中,创建行
    HSSFRow row = sheet.createRow(0);
    //4.在当前行中,创建单元格
    HSSFCell cell = row.createCell(0);
    //5.①.给单元格设置字符串值
    cell.setCellValue("不要迷恋哥,哥只是个传说!");
    
    //②.给单元格设置布尔型值
    HSSFCell cell2 = row.createCell(1);
    cell2.setCellValue(true);
    //③.给单元格设置整数值
    HSSFCell cell3 = row.createCell(2);
    cell3.setCellValue(10);
    
    HSSFCell cell4 = row.createCell(3);
    cell4.setCellValue(3.4);
    
    //④.给单元格设置时间值
    HSSFCell cell5 = row.createCell(4);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = sdf.parse("1990-12-12 10:38:40");
    cell5.setCellValue(date);
    
    //⑤.给单元格设置Calendar时间
    HSSFCell cell6 = row.createCell(5);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 1990);
    calendar.set(Calendar.MONTH,12);
    calendar.set(Calendar.DAY_OF_MONTH,20);
    calendar.set(Calendar.HOUR,10);
    calendar.set(Calendar.MINUTE,50);
    calendar.set(Calendar.SECOND,55);
    
    cell6.setCellValue(calendar);
    //6.创建输出流,写入到硬盘上!
    FileOutputStream out = new FileOutputStream("d:\text.xls");
    workbook.write(out);
    }
    View Code

    三、调整工作表格式

    为了避免处理工作表数据时内存溢出,相关对象要尽可能重用,而不是每次都创建新的。
      HSSFDataFormat format = workbook.createDataFormat();

    ①.日期格式
      HSSFCellStyle styleDate = workbook.createCellStyle();
      styleDate.setDataFormat(format.getFormat("yyyy/MM/dd HH:dd:ss"));

    ③.回绕文本
      HSSFCellStyle styleWrapText = workbook.createCellStyle();
      styleWrapText.setWrapText(true);

      ④.指定列宽:单位1/20像素
        sheet.setColumnWidth(columnIndex,width);


        案例:设置时间的格式

    @Test
    public void test() throws Exception {
    //1.创建代表Excel文件的HSSFWorkBook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    //2.在当前Excel文件中创建工作表
    HSSFSheet sheet = workbook.createSheet();
    //3.在当前工作表中,创建行
    HSSFRow row = sheet.createRow(0);
    
    HSSFDataFormat dataFormat = workbook.createDataFormat();
    short format = dataFormat.getFormat("yyyy-MM-dd HH:mm:ss");
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(format);
    //④.给单元格设置时间值
    HSSFCell cell5 = row.createCell(4);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = sdf.parse("1990-12-12 10:38:40");
    cell5.setCellValue(date);
    cell5.setCellStyle(cellStyle);
    
    //⑤.给单元格设置Calendar时间
    HSSFCell cell6 = row.createCell(5);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 1990);
    calendar.set(Calendar.MONTH,12);
    calendar.set(Calendar.DAY_OF_MONTH,20);
    calendar.set(Calendar.HOUR,10);
    calendar.set(Calendar.MINUTE,50);
    calendar.set(Calendar.SECOND,55);
    
    cell6.setCellValue(calendar);
    cell6.setCellStyle(cellStyle);
    
    }
    View Code

           案例:设置回绕文本

    @Test
    public void test() throws Exception {
    //1.创建代表Excel文件的HSSFWorkBook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    //2.在当前Excel文件中创建工作表
    HSSFSheet sheet = workbook.createSheet();
    //3.在当前工作表中,创建行
    HSSFRow row = sheet.createRow(0);
    
    HSSFCell cell = row.createCell(0);
    cell.setCellValue("这是一个回绕文本数据哦!!!!!!!!!");
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setWrapText(true);
    cell.setCellStyle(cellStyle);
    
    //6.创建输出流,写入到硬盘上!
    FileOutputStream out = new FileOutputStream("d:\text.xls");
    workbook.write(out);
    }
    View Code

        案例:设置固定列宽

    @Test
    public void test() throws Exception {
    //1.创建代表Excel文件的HSSFWorkBook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    //2.在当前Excel文件中创建工作表
    HSSFSheet sheet = workbook.createSheet();
    //设置固定列宽
    sheet.setColumnWidth(1,10000);
    //3.在当前工作表中,创建行
    HSSFRow row = sheet.createRow(0);
    
    HSSFCell cell = row.createCell(0);
    cell.setCellValue("这是一个回绕文本数据哦!!!!!!!!!");
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setWrapText(true);
    cell.setCellStyle(cellStyle);
    
    //6.创建输出流,写入到硬盘上!
    FileOutputStream out = new FileOutputStream("d:\text.xls");
    workbook.write(out);
    }
    View Code

    四、在项目中使用POI

    1、导入jar包

    commons-codec-1.5.jar
    poi-3.9-20121203.jar

    2.导出方式:使用stream结果类型

    ①提供文件输入流:inputstream
    ②提供文件名:fileName

    @Component
    public class MyView extends AbstractView{
    
    @Override
    protected void renderMergedOutputModel(Map<String, Object> map,
    HttpServletRequest request, HttpServletResponse response) throws Exception {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFDataFormat format = wb.createDataFormat();
    HSSFCellStyle style = wb.createCellStyle();
    
    HSSFSheet sheet = wb.createSheet("sheet001");
    HSSFRow row = sheet.createRow(0);
    
    style = wb.createCellStyle();
    
    HSSFCell cell = row.createCell(1);
    System.out.println(map.get("name"));
    cell.setCellValue((String)(map.get("name")));
    cell.setCellStyle(style);
    sheet.autoSizeColumn(1);
    response.setContentType("application/vnd.ms-excel");
    String fileName = "DFS.xls";
    response.setHeader("Content-Disposition","attachment; filename="+fileName);
    wb.write(response.getOutputStream());
    
    }
    }
    View Code




















  • 相关阅读:
    MATLAB批量读入图片
    MATLAB小技巧
    Ubuntu下OpenCV不能被某个python版本识别
    切换Ubuntu系统python默认版本的方法
    LoadRunner内部结构(2)
    LoadRunner例子:检查点为参数的一个例子
    LoadRunner中字符串的操作
    LoadRunner脚本实例来验证参数化的取值
    LoadRunner编程之文件的操作
    LoadRunner关联函数的脚本实例--如何操作关联参数
  • 原文地址:https://www.cnblogs.com/bkyy/p/8386123.html
Copyright © 2020-2023  润新知