zoukankan      html  css  js  c++  java
  • java学习之导出Excel

    1. 输出表格

    poi输出excel最基本是输出table表格,下面是输出区域、总销售额(万元)、总利润(万元)简单的表格,创建HSSFWorkbook 对象,用于将excel输出到输出流中

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("table");  //创建table工作薄
    Object[][] datas = {{"区域", "总销售额(万元)", "总利润(万元)简单的表格"}, {"江苏省" , 9045,  2256}, {"广东省", 3000, 690}};
    HSSFRow row;
    HSSFCell cell;
    for(int i = 0; i < datas.length; i++) {
        row = sheet.createRow(i);// 创建表格行
        for(int j = 0; j < datas[i].length; j++) {
            cell = row.createCell(j);// 根据表格行创建单元格
            cell.setCellValue(String.valueOf(datas[i][j]));
        }
    }
    wb.write(new FileOutputStream("/Users/mike/table.xls"));

    2. 设置表格行高和列宽

      有时表格文本比较多,需要设置表格的列宽度,在设置表格的行高与列宽时一定在创建全部的HSSFRow与HSSFCell之后,即整个表格创建完成之后去设置,因为在单元格合并的时候,合并之前设置的宽度单元格会比设置的宽度更宽。 sheet.setColumnWidth 设置列宽值需要转换为excel的宽度值,使用工具类:MSExcelUtil,excel宽度并不是像素需要转换

    //创建表格之后设置行高与列宽
    for(int i = 0; i < datas.length; i++) {
        row = sheet.getRow(i);
        row.setHeightInPoints(30);// 设置行高
    }
    for(int j = 0; j < datas[0].length; j++) {
        sheet.setColumnWidth(j, MSExcelUtil.pixel2WidthUnits(160)); // 设置列宽
    }

    3. 设置excel单元格样式

      单元格可以设置居左、居中、居右、上下居中、设置边框、设置边框颜色、设置单元格背景颜色等, excel设置单元格有一个HSSFCellStyle类可以设置样式,单元格颜色比较麻烦,excel颜色对应一个下标值,我们可以使用自定义颜色,但下标值从11开始,前1-10被poi已经使用,通过palette.setColorAtIndex方法将颜色与下标值对应,下面cellStyle.setFillForegroundColor(bgIndex)设置背景颜色时set 下标值并不是颜色Color,一个下标值如11不能被重复设置颜色,否则excel单元格显示的都是黑色,如下背景颜色使用下标值bgIndex=11,边框颜色使用下标值bdIndex=12

    short colorIndex = 10;
    HSSFPalette palette = wb.getCustomPalette();//自定义颜色
    Color rgb = Color.GREEN;
    short bgIndex = colorIndex ++; //背景颜色下标值
    palette.setColorAtIndex(bgIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue());
    short bdIndex = colorIndex ++; //边框颜色下标值
    rgb = Color.BLACK;
    palette.setColorAtIndex(bdIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue());
     
    for(int i = 0; i < datas.length; i++) {
        row = sheet.createRow(i);//创建表格行
        for(int j = 0; j < datas[i].length; j++) {
            cell = row.createCell(j);//根据表格行创建单元格
            cell.setCellValue(String.valueOf(datas[i][j]));
     
            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setFillForegroundColor(bgIndex); //bgIndex 背景颜色下标值
            cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
     
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //bdIndex 边框颜色下标值
            cellStyle.setBottomBorderColor(bdIndex);
            cellStyle.setLeftBorderColor(bdIndex);
            cellStyle.setRightBorderColor(bdIndex);
            cellStyle.setTopBorderColor(bdIndex);
     
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
     
            cell.setCellStyle(cellStyle);
        }
    }

    4. 单元格文本设置字体样式

    单元格文本可设置字体大小、颜色、斜体、粗体、下划线等。

    HSSFCellStyle cellStyle = wb.createCellStyle();
     
    HSSFFont font = wb.createFont();
    font.setColor(HSSFColor.RED.index); // 字体颜色   
    font.setFontHeightInPoints((short)30);//字号设置字体大小  
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
    font.setItalic(true);
    font.setUnderline(HSSFFont.U_SINGLE);
    font.setFontHeightInPoints((short)14);
    cellStyle.setFont(font);

    5. 合并单元格

    sheet中可以类似html合并单元格,指定开始行(从0开始计算)、合并单元格最后行、开始列(从0开始)、 合并单元格最后列四个参数值

    CellRangeAddress region = new CellRangeAddress(0, // first row
            0, // last row
            0, // first column
            2 // last column
    );
    sheet.addMergedRegion(region);

    6. 单元格加入图片

    插入图片最主要的用到HSSFClientAnchor,HSSFClientAnchor的文档介绍如下:

    public HSSFClientAnchor(int dx1,
                    int dy1,
                    int dx2,
                    int dy2,
                    short col1,
                    int row1,
                    short col2,
                    int row2)
    Parameters:
    dx1 - the x coordinate within the first cell.//定义了图片在第一个cell内的偏移x坐标,既左上角所在cell的偏移x坐标,一般可设0
    dy1 - the y coordinate within the first cell.//定义了图片在第一个cell的偏移y坐标,既左上角所在cell的偏移y坐标,一般可设0
    dx2 - the x coordinate within the second cell.//定义了图片在第二个cell的偏移x坐标,既右下角所在cell的偏移x坐标,一般可设0
    dy2 - the y coordinate within the second cell.//定义了图片在第二个cell的偏移y坐标,既右下角所在cell的偏移y坐标,一般可设0
    col1 - the column (0 based) of the first cell.//第一个cell所在列,既图片左上角所在列
    row1 - the row (0 based) of the first cell.//图片左上角所在行
    col2 - the column (0 based) of the second cell.//图片右下角所在列
    row2 - the row (0 based) of the second cell.//图片右下角所在行
    public class ExcelExport {  
      
        public static void main(String[] args) {  
             FileOutputStream fileOut = null;     
             BufferedImage bufferImg = null;     
            try {  
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();  
              //加载图片  
                bufferImg = ImageIO.read(new File("e:/1.jpg"));     
                ImageIO.write(bufferImg, "jpg", byteArrayOut);  
                HSSFWorkbook wb = new HSSFWorkbook();     
                HSSFSheet sheet1 = wb.createSheet("sheet1");    
                HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();     
                /** 
                    dx1 - the x coordinate within the first cell.//定义了图片在第一个cell内的偏移x坐标,既左上角所在cell的偏移x坐标,一般可设0 
                    dy1 - the y coordinate within the first cell.//定义了图片在第一个cell的偏移y坐标,既左上角所在cell的偏移y坐标,一般可设0 
                    dx2 - the x coordinate within the second cell.//定义了图片在第二个cell的偏移x坐标,既右下角所在cell的偏移x坐标,一般可设0 
                    dy2 - the y coordinate within the second cell.//定义了图片在第二个cell的偏移y坐标,既右下角所在cell的偏移y坐标,一般可设0 
                    col1 - the column (0 based) of the first cell.//第一个cell所在列,既图片左上角所在列 
                    row1 - the row (0 based) of the first cell.//图片左上角所在行 
                    col2 - the column (0 based) of the second cell.//图片右下角所在列 
                    row2 - the row (0 based) of the second cell.//图片右下角所在行 
                 */  
                HSSFClientAnchor anchor = new HSSFClientAnchor(-100, 0, 0, 0,(short) 2, 2, (short) 5, 8);     
                // 插入图片1   
                patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));  
           // 插入图片2
    anchor = new HSSFClientAnchor(200, 0, 0, 0,(short) 2, 9, (short) 5, 15);  
    patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
           fileOut = new FileOutputStream("e:/excel.xls");
          // 输出文件
           wb.write(fileOut);
     } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    }

     插入图片备注:

    HSSFSheet sheet = workbook.createSheet("Test");// 创建工作表(Sheet)
    FileInputStream stream=newFileInputStream("d:\POI\Apache.gif");
    byte[] bytes=new byte[(int)stream.getChannel().size()];
    stream.read(bytes);//读取图片到二进制数组
    int pictureIdx = workbook.addPicture(bytes,HSSFWorkbook.PICTURE_TYPE_JPEG);
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,(short)0, 0, (short)5, 5);
    HSSFPicture pict = patriarch.createPicture(anchor,pictureIdx);
    //pict.resize();//自动调节图片大小,图片位置信息可能丢失
  • 相关阅读:
    github使用
    部署flask
    docker部署路飞学城
    centos7安装dnsmasq局域网dns
    消息队列rabbitmq
    记录腾讯云中矿机病毒处理过程(重装系统了fu*k)
    Golang基础
    git协同开发
    gitlab与pycharm结合
    github与gitlab与git三个基佬的故事
  • 原文地址:https://www.cnblogs.com/sunfie/p/7778949.html
Copyright © 2011-2022 走看看