POI导出Excel及单元格的设置

1、POI的导出Excel的两种方式操作:

SXSSFWorkbook  .xlsx

HSSFWorkbook .xls

如下代码时实现Excel的表单代码:


import java.io.File;
import java.io.FileOutputStream;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test;

public class XlsxTest {

/**
* SXSSFWorkbook .xlsx
* @throws Exception
*/

@Test
public void test1() throws Exception{
SXSSFWorkbook workbook=new  SXSSFWorkbook();
FileOutputStream fos = new FileOutputStream(new File("E://TestbyJava//456.xlsx"));
Sheet sheet = workbook.createSheet();

// 创建列宽
sheet.setColumnWidth(0, 2800);
sheet.setColumnWidth(1, 4500);
sheet.setColumnWidth(2, 4500);
sheet.setColumnWidth(3, 4500);
sheet.setColumnWidth(4, 4500);

CellStyle style=getStyle(workbook);

Row row0 = sheet.createRow(0);
Cell cell_1 = row0.createCell((short) 0);
cell_1.setCellValue("认证途径人流量统计表");
cell_1.setCellStyle(style);
row0.setHeightInPoints(22);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));

row0 = sheet.createRow(1);
cell_1 = row0.createCell((short) 0);
cell_1.setCellValue("时间范围:");
cell_1.setCellStyle(style);

cell_1 = row0.createCell(1);
CellStyle dateCellStyle=workbook.createCellStyle();
short df=workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss");
dateCellStyle.setDataFormat(df);
cell_1.setCellStyle(dateCellStyle);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));

row0 = sheet.createRow(2);
cell_1 = row0.createCell(0);
cell_1.setCellValue("序号"); 
cell_1.setCellStyle(style);
           
cell_1 = row0.createCell(1);
cell_1.setCellValue("认证途径");
cell_1.setCellStyle(style);

cell_1 = row0.createCell(2);
cell_1.setCellValue("人流量");
cell_1.setCellStyle(style);
           
cell_1 = row0.createCell(3);
cell_1.setCellValue("已关注");
cell_1.setCellStyle(style);
           
cell_1 = row0.createCell(4);
cell_1.setCellValue("未关注");
cell_1.setCellStyle(style);
workbook.write(fos);
        fos.flush();
        fos.close();
System.out.println(sheet.toString());
}

/**
* HSSFWorkbook .xls
* @throws Exception
*/
@Test
public void test2() throws Exception{
HSSFWorkbook wb =new HSSFWorkbook(); 
FileOutputStream fos = new FileOutputStream(new File("E://TestbyJava//123.xls"));
HSSFSheet sh = wb.createSheet();

        sh.setColumnWidth( 0, 3500);
        sh.setColumnWidth( 1, 6000);  
        sh.setColumnWidth( 2, 6000);  
        sh.setColumnWidth( 3, 6000);  
        sh.setColumnWidth( 4, 6000);  
        
        // 第一行表头标题,CellRangeAddress 参数:行 ,行, 列,列
        HSSFRow row = sh.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue(new HSSFRichTextString("认证途径人流量统计表"));
        cell.setCellStyle(getStyle1(wb));
        sh.addMergedRegion(new CellRangeAddress(0, 0, 0,2));
        
        row = sh.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue(new HSSFRichTextString("时间范围:"));
        cell.setCellStyle(getStyle1(wb));
        sh.addMergedRegion(new CellRangeAddress(1, 1, 0, 0));


        cell = row.createCell(1);
        cell.setCellStyle(getStyle1(wb));
        sh.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
        
        row = sh.createRow(2);
        cell = row.createCell(0);
        cell.setCellValue(new HSSFRichTextString("序号")); 
        cell.setCellStyle(getStyle1(wb));
        
        cell = row.createCell(1);
        cell.setCellValue(new HSSFRichTextString("认证途径"));
        cell.setCellStyle(getStyle1(wb));

        cell = row.createCell(2);
        cell.setCellValue(new HSSFRichTextString("人流量"));
        cell.setCellStyle(getStyle1(wb));
        
        cell = row.createCell(3);
        cell.setCellValue(new HSSFRichTextString("已关注"));
        cell.setCellStyle(getStyle1(wb));
        
        cell = row.createCell(4);
        cell.setCellValue(new HSSFRichTextString("未关注"));
        cell.setCellStyle(getStyle1(wb));
        wb.write(fos);
        fos.flush();
        fos.close();
System.out.println("======="+sh.toString());
}

private CellStyle getStyle(SXSSFWorkbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 设置单元格字体
Font headerFont = workbook.createFont(); // 字体
headerFont.setFontHeightInPoints((short) 14);
style.setFont(headerFont);
style.setWrapText(true);
return style;
}

private HSSFCellStyle getStyle1(HSSFWorkbook workbook) {
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 设置单元格字体
Font headerFont = workbook.createFont(); // 字体
headerFont.setFontHeightInPoints((short) 14);
style.setFont(headerFont);
style.setWrapText(true);
return style;
}
}

效果图:



2、从数据库导出表单的相关类及参数的简单介绍

ReportForAuthenServicepoi      导出类 

exportExcel(ReportBean reportBean ) 导出方法,reportBean参数为表单参数

ReportForAuthenBean  表单填充的数据需要调用的类,数据来源于数据库


3、相关代码如下:


import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;


import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;  //对Excel 97(-2007)文件操作的纯Java实现
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;

/**
 * 导出认证类型人流量统计表
 * @author Allen
 * @since: v1.0
 */
public class ReportForAuthenServicepoi {
private final static Logger logger = Logger.getLogger(ReportForAuthenService.class);

    HSSFWorkbook wb; 
    FileOutputStream fos;

    /** 
  * 导出报表
  * 
  * @param reportBean     
* @throws Exception 
  */
public String exportExcel(ReportBean reportBean ) throws Exception {
        try {    
            String fileName = "认证途径人流量统计表_";
            if(StringUtils.stringNotEmpty(reportBean.getTimeType())){
            fileName += DateUtils.toString(new Date(), "yyyyMMdd") + "-" + reportBean.getTimeType();
            }else{
            fileName += reportBean.getBeginTime().replace("-", "")+"_"+reportBean.getEndTime().replace("-", "");
            }
            if(StringUtils.stringNotEmpty(reportBean.getShopName())){
            fileName +="_"+reportBean.getShopName();
            }
            if(reportBean.getAuthenType() != null){
            fileName +="_"+reportBean.getAuthenType().getMessage();
            }
            if(StringUtils.stringNotEmpty(reportBean.getWlcName())){
            fileName += "_" + reportBean.getWlcName();
            }
            fileName = fileName.replace(".", ",");
            fileName +=".xls";
            List<ReportForAuthenBean> reportForVisitorBeans = WifiUserReportService.reportAuthen(reportBean);
            fos = new FileOutputStream(WifiUserReportService.REPORT_PATH + fileName);
            wb= new HSSFWorkbook(); 
           
            HSSFSheet sh = wb.createSheet();
            sh.setColumnWidth( 0, 256*15+184);
            sh.setColumnWidth( 1, 256*30+184);  
            sh.setColumnWidth( 2, 256*30+184);  
            sh.setColumnWidth( 3, 256*30+184);  
            sh.setColumnWidth( 4, 256*30+184);  
            
            // 第一行表头标题,CellRangeAddress 参数:行 ,行, 列,列
            HSSFRow row = sh.createRow(0);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString("认证途径人流量统计表"));
            cell.setCellStyle(HSSFFontUtils.headFont(wb));
            sh.addMergedRegion(new CellRangeAddress(0, 0, 0,2));
            
            HSSFRow row1 = sh.createRow(1);
            cell = row1.createCell(0);
            cell.setCellValue(new HSSFRichTextString("时间范围:"));
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));
            sh.addMergedRegion(new CellRangeAddress(1, 1, 0, 0));


            cell = row1.createCell(1);
            if(StringUtils.stringNotEmpty(reportBean.getTimeType())){
                cell.setCellValue(DateUtils.toString(new Date(), "yyyyMMdd") + "-" + reportBean.getTimeType());
            }else{
                cell.setCellValue(reportBean.getBeginTime()+ "至" + reportBean.getEndTime());
            }
            cell.setCellStyle(HSSFFontUtils.dateFont(wb));
            sh.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
            
            if(StringUtils.stringNotEmpty(reportBean.getShopName())){
                cell = row1.createCell(2);
                cell.setCellValue(new HSSFRichTextString("店铺:" + reportBean.getShopName()));
                cell.setCellStyle(HSSFFontUtils.cloFont(wb));
                sh.addMergedRegion(new CellRangeAddress(1, 1, 3, 4));
            }
            
            HSSFRow row3 = sh.createRow(2);
            cell = row3.createCell(0);
            cell.setCellValue(new HSSFRichTextString("序号")); 
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));
            
            cell = row3.createCell(1);
            cell.setCellValue(new HSSFRichTextString("认证途径"));
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));


            cell = row3.createCell(2);
            cell.setCellValue(new HSSFRichTextString("人流量"));
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));
            
            cell = row3.createCell(3);
            cell.setCellValue(new HSSFRichTextString("已关注"));
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));
            
            cell = row3.createCell(4);
            cell.setCellValue(new HSSFRichTextString("未关注"));
            cell.setCellStyle(HSSFFontUtils.cloFont(wb));
            
            //填充数据的内容  i表示行,j表示表单的编号数,z表示数据库某表的数据大小,这里使用它作为遍历条件
            int i = 3, j = 1, z = 0;
            ReportForAuthenBean reportForVisitorBean=new ReportForAuthenBean();
            while(z<reportForVisitorBeans.size()){
            reportForVisitorBean=reportForVisitorBeans.get(z);
            row = sh.createRow(i);
            row.createCell(0).setCellValue(new HSSFRichTextString(String.valueOf(j)));
                row.createCell(1).setCellValue(new HSSFRichTextString(reportForVisitorBean.getAuthenType().getMessage()));
                row.createCell(2).setCellValue(Double.parseDouble(reportForVisitorBean.getCount()));
                row.createCell(3).setCellValue(Double.parseDouble(reportForVisitorBean.getSubscribe()));
                row.createCell(4).setCellValue(Double.parseDouble(reportForVisitorBean.getUnsubscribe()));
                i++;
            j++;
            z++;
            }
            wb.write(fos);
            return WifiUserReportService.REPORT_PATH + fileName;
        }catch (Exception e){
        logger.error("[ReportForAuthenService]==> 生成认证途径人流量统计表失败:,异常信息:", e);
}finally {
try {
if(fos != null){
fos.close();
}
}
catch (Exception e) {
logger.error("[ReportForAuthenService]==> 关闭流失败,异常信息:", e);
}
}
return null;
    }
}
    


4、表单样式处理类

package com.krycai.report.util;


import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 处理表头样式
 * @author Allen
 *
 */
public class HSSFFontUtils {
 
// 表头标题样式
public static HSSFCellStyle headFont(HSSFWorkbook wb){
HSSFCellStyle style = wb.createCellStyle();
   HSSFFont headfont = wb.createFont();
   headfont.setFontName("宋体");
   headfont.setFontHeightInPoints((short) 12);// 字体大小
   style.setFont(headfont);
   style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
   style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
   style.setLocked(true); 
   return style;
}

// 表头时间样式
public static HSSFCellStyle dateFont(HSSFWorkbook wb){
        HSSFFont datefont = wb.createFont();
        datefont.setFontName("宋体");
        datefont.setFontHeightInPoints((short) 12);// 字体大小
        HSSFCellStyle style = wb.createCellStyle();
        style.setFont(datefont);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        style.setLocked(true); 
   return style;
}

// 表头列名样式
public static HSSFCellStyle cloFont(HSSFWorkbook wb){
HSSFFont font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 12);// 字体大小
        HSSFCellStyle style = wb.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        style.setLocked(true); 
return style;
}

//表头普通样式
public static HSSFCellStyle normalFont(HSSFWorkbook wb){
HSSFFont font2 = wb.createFont();
        font2.setFontName("宋体");
        font2.setFontHeightInPoints((short) 12);
        HSSFCellStyle style = wb.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        style.setFont(font2);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setWrapText(true); // 换行
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中

return style;
}
}


效果图:



生手,写的比较粗糙,请多多指教。

猜你喜欢

转载自blog.csdn.net/baidu_28068985/article/details/77160268