poi 打印 excel 生成工作表

package com.wondersgroup.wdls.common.excel;
 
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
 
public class ExcelPrintA4Utils {
 
    // 显示的导出Excel表的标题(通常第一行)
    private String title;
    // 导出Excel表的列名(通常第二行)
    private String[] rowName;
    // 导出Excel表的文件名
    private String fileName;
 
    // 导出Excel表的文件主题内容(通常从第三行往下的内容)
    // 需要注意的是:主要内容的格式为第一列为数字(序号),从第二列开始都是字符串
    // 每一行为Object[]类型,很多行用List包装起来
    private List<Object[]> dataList = new ArrayList<Object[]>();
    // 用于下载的response
    private HttpServletResponse response;
    
    // 构造方法,传入要导出的数据
    public ExcelPrintA4Utils(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse response, String fileName) {
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.response = response;
        this.fileName = fileName;
    }
 
    /**
     * @Description 设置单元格样式
     * @Author zhulei
     * @Date 2021/1/26 14:57
     * @Param wb:工作薄
     * @Return 单元格样式
     */
    public static CellStyle getCellStyle(Workbook wb){
        // 设置字体
        Font font = wb.createFont();
        //设置字体名字
        font.setFontName("微软雅黑");
        //设置样式;
        CellStyle style = wb.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(IndexedColors.BLACK.index);
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(IndexedColors.BLACK.index);
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        设置右边框颜色;
        style.setRightBorderColor(IndexedColors.BLACK.index);
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(IndexedColors.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
 
        return style;
    }
 
    /**
     * @Description 单元格合并
     * @Author zhulei
     * @Date 2021/1/26 15:07
     * @Param
     * @Return
     */
    public static Sheet mergeCell(Sheet sheet,int firstRow, int lastRow, int firstCol, int lastCol){
        CellRangeAddress region = new CellRangeAddress(firstRow,lastRow,firstCol,lastCol);//获取区域从第firstRow行-lastRow行,firstCol列-lastCol列
        sheet.addMergedRegion(region);// 合并region的区域
        return sheet;
    }
    
    /**
     * @Description 标题样式
     * @Author zhulei
     * @Date 2021/1/26 15:35
     * @Param 
     * @Return 
     */
    public CellStyle getTitleStyle(Workbook wb) {
 
        // 设置字体
        Font font = wb.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 24);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName("微软雅黑");
        //设置样式;
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
    /**
     * @Description 列头样式
     * @Author zhulei
     * @Date 2021/1/27 15:34
     * @Param
     * @Return
     */
    public CellStyle getColumnTopStyle(Workbook wb) {
 
        // 设置字体
        Font font = wb.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName("微软雅黑");
        //设置样式;
        CellStyle style = wb.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(IndexedColors.BLACK.index);
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(IndexedColors.BLACK.index);
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(IndexedColors.BLACK.index);
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(IndexedColors.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
    /**
     * @Description A4纸打印
     * @Author zhulei
     * @Date 2021/1/26 16:02
     * @Param
     * @Return
     */
    public static void printA4(Sheet sheet) {
        // 设置打印
        HSSFPrintSetup printSetup = (HSSFPrintSetup) sheet.getPrintSetup();
        printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
        printSetup.setLandscape(true); // 打印方向,true:横向,false:纵向(默认)
 
        printSetup.setVResolution((short)600);
        printSetup.setScale((short)50);//自定义缩放,此处100为无缩放
 
        sheet.setHorizontallyCenter(true);//设置打印页水平居中
        sheet.setVerticallyCenter(false); //设置打印页面为垂直居中
        sheet.setAutobreaks(false);//true设置sheet适应于一页,false设置sheet不一定适应于一页
 
    }
 
    public static void main(String[] args) throws IOException {
        Workbook wb = new HSSFWorkbook();//定义一个新的工作薄
        Sheet sheet = wb.createSheet("sheet");//创建一个sheet
 
        //设置不显示excel网格线
        sheet.setDisplayGridlines(false);//其中sheet是Sheet对象
        printA4(sheet);//设置A4打印
 
        for(int i=0;i<30;i++){
            Row row = sheet.createRow(i);//创建行
            Cell cell = row.createCell(0);//获取行单元格
            cell.setCellValue("测试excle"+i);//给行单元格设置值
 
            //设置每pagingRow(15)行分页打印
            if ((i+1) % 5 == 0){
                sheet.setRowBreak(i);//設置每15行分頁打印
            }
 
            //设置单元格边框
            cell.setCellStyle(getCellStyle(wb));
 
        }
 
        //合并单元格
//        merge(sheet,2,1);
 
 
        //4.设置页脚的页数
        HSSFFooter footer = (HSSFFooter )sheet.getFooter();
        footer.setCenter( "第" + HSSFFooter.page() + "页/共" + HSSFFooter.numPages()+"页");
 
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\测试工作薄.xls");
        wb.write(fos);
        fos.close();
    }
 
    // 下载Excel的方法
    public void downloadExcel() {
        try {
            Workbook workbook = new HSSFWorkbook();// 创建工作簿对象
            Sheet sheet = workbook.createSheet(title);// 创建工作表
 
            //设置不显示excel网格线
            sheet.setDisplayGridlines(false);//其中sheet是Sheet对象
 
            //设置页脚的页数
            HSSFFooter footer = (HSSFFooter )sheet.getFooter();
            footer.setCenter( "第" + HSSFFooter.page() + "页/共" + HSSFFooter.numPages()+"页");
 
            CellStyle columnTopStyle = getColumnTopStyle(workbook);//获取列头样式对象
            CellStyle titleStyle = getTitleStyle(workbook);//获取标题样式
 
 
            /*单元格处理*/
            CellStyle style = getCellStyle(workbook);//单元格样式对象
 
 
            int listCount = dataList.size();//数据数量
            int ys = listCount % 10;//余数
            int page = listCount/10;//页数
            int allrowCount = 0;
            if(ys==0){
                allrowCount = dataList.size()+(page*5);
            }else {
                allrowCount = dataList.size()+((page+1)*5);
            }
            int index = 0;//初始化行Index
 
            // 定义列头所需列数
            int columnNum = rowName.length;
            // 将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < listCount; i++) { //遍历每个对象
 
                if (index>=allrowCount) break;
 
                Object[] obj = dataList.get(i);
 
                printA4(sheet);//设置A4打印
                //设置每pagingRow(14)行分页打印
                if (index!=0&&index % 14== 0){
                    sheet.setRowBreak(index-1);//設置每14行分頁打印
                }
 
                //设置每页前四行的值
                if(index%14==0){
                    /*标题处理*/
                    // 产生表格标题行(占用两行)
                    Row rowm = sheet.createRow(index);
                    rowm.setHeight((short)(47.25*20));
                    Cell cell = rowm.createCell(0);
 
                    //合并标题占用的两行
                    mergeCell(sheet,index,index+2,0,(rowName.length - 1));
 
                    cell.setCellStyle(titleStyle);//标题赋样式
                    cell.setCellValue(title);//标题赋值
                    index = index+2;//完成两行数据设置值,给行index+2
 
                    //标题下的年度号
                    Row row2 = sheet.createRow(index);
                    cell = row2.createCell(0);
                    cell.setCellValue("font");
                    cell.setCellStyle(titleStyle);
                    index = index+1;//完成一行数据设置值,给行index+1
 
 //                  将列头设置到sheet的单元格中(占一行)
                    Row rowRowName = sheet.createRow(index);// 在索引2的位置创建行(最顶端的行开始的第二行)
                    rowRowName.setHeight((short)(30*20));
                    for (int n = 0; n < columnNum; n++) {
                        Cell cellRowName = rowRowName.createCell(n);//创建列头对应个数的单元格
                        cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型
                        HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                        cellRowName.setCellValue(text);  //设置列头单元格的值
                        cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
                    }
 
                    index = index+1;//完成一行数据设置值,给行index+1
                }
 
                Row row = sheet.createRow(index);//创建所需的行数
                for (int j = 0; j < obj.length; j++) {
                    row.setHeight((short)(62.5*20));
                    Cell cell2 = null;  //设置单元格的数据类型
                    if (j == 0) {
                        cell2 = row.createCell(j,CellType.NUMERIC); //第一列为数字
                        cell2.setCellValue(i + 1);
                    } else {
                        cell2 = row.createCell(j,CellType.STRING); //第一列为字符
                        if (!"".equals(obj[j]) && obj[j] != null) {
                            cell2.setCellValue(obj[j].toString()); //设置单元格的值
                        }else{
                            cell2.setCellValue("");
                        }
                    }
                    cell2.setCellStyle(style);  //设置单元格样式
                }
                index = index+1;//完成一行数据设置值,给行index+1
            }
            //让列宽随着导出的列长自动适应
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    Row currentRow;
                    //当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        Cell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellTypeEnum() == CellType.STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    if(columnWidth > 255){
                        columnWidth = 255;
                    }
                    sheet.setColumnWidth(colNum, columnWidth* 256);
                }
            }
//            printA4(sheet);
 
            if (workbook != null) {
                try {
                    if (response != null) {
                        response.setContentType("application/vnd.ms-excel;charset=utf-8");
                        response.setHeader("Content-Disposition", "attachment;filename=\""+new String(fileName.getBytes("gb2312"),"ISO8859-1"));
                        OutputStream out = response.getOutputStream();
                        workbook.write(out);
                        out.close();
                    } else {
                        FileOutputStream outputStream = new FileOutputStream("C:/"+fileName);
                        workbook.write(outputStream);
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你好,我理解你的问题是关于使用POI生成Excel的问题。 首先,POI是一个开源的Java库,可用于读取和写入Microsoft Office格式的文档,包括Excel电子格文件。使用POI生成Excel文件通常需要遵循以下步骤: 1. 创建一个工作簿对象:使用HSSFWorkbook类(对于xls格式的Excel)或XSSFWorkbook类(对于xlsx格式的Excel)创建一个新的工作簿对象。 2. 创建一个工作对象:使用createSheet方法创建一个新的工作对象。 3. 创建行对象:使用createRow方法创建一个新的行对象。 4. 创建单元格对象:使用createCell方法创建一个新的单元格对象。 5. 写入数据:使用setCellValue方法将数据写入单元格对象。 6. 保存文件:使用write方法将工作簿对象写入文件。 在生成Excel文件之前,你需要确定所需的数据并将其准备好,然后按照上述步骤使用POI将数据写入Excel文件。 如果你遇到了特定的问题或错误,请提供更多细节或错误信息,以便我能够更好地帮助你。 ### 回答2: POI是一款Java开发的开源库,可以用于生成和操作Microsoft Office格式的文件,包括Excel。 使用POI生成Excel文件的步骤如下: 1. 首先,需要导入POI的相关jar包,包括poi-<version>.jar、poi-ooxml-<version>.jar和poi-ooxml-schemas-<version>.jar。 2. 创建一个工作簿对象(Workbook),可以根据需要选择创建HSSFWorkbook(用于处理xls格式)或XSSFWorkbook(用于处理xlsx格式)。 3. 创建一个工作对象(Sheet),可以使用createSheet方法创建一个新的工作,并设置工作名称。 4. 在工作中创建行(Row)和单元格(Cell)。 5. 使用setCellValue方法设置单元格的值。 6. 根据需要,可以设置单元格的样式,如字体、颜色等。 7. 使用FileOutputStream将工作簿写入文件。 下面是一个简单的示例代码,通过POI生成一个包含员工信息的Excel文件: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; public class ExcelGenerator { public static void main(String[] args) { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作 Sheet sheet = workbook.createSheet("员工信息"); // 创建行 Row row = sheet.createRow(0); // 创建单元格,并设置值 Cell cell1 = row.createCell(0); cell1.setCellValue("姓名"); Cell cell2 = row.createCell(1); cell2.setCellValue("年龄"); Cell cell3 = row.createCell(2); cell3.setCellValue("性别"); // 将工作簿写入文件 try (FileOutputStream fileOut = new FileOutputStream("员工信息.xlsx")) { workbook.write(fileOut); System.out.println("Excel文件生成成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 通过以上步骤,我们可以使用POI生成包含指定内容的Excel文件,并保存在指定路径中。使用POI可以灵活地生成各种Excel文件,满足不同的需求。 ### 回答3: POI是一种Java库,用于生成和操作Microsoft Excel格式的电子格文件。使用POI,我们可以编写程序来生成Excel文件,并对其进行各种操作。 首先,我们需要导入POI库到我们的Java项目中。然后,我们可以通过创建Workbook对象来创建Excel文件。Workbook对象是Excel文件的顶级对象,可以包含多个Sheet对象。 接下来,我们可以创建Sheet对象,并通过向它添加行和单元格来填充数据。可以使用Row和Cell对象来操作行和单元格。可以设置行高、列宽、单元格样式等来定制Excel的外观。 我们可以使用不同的数据类型来填充单元格,如字符串、数字、日期等。还可以应用公式和函数来计算单元格的值。可以使用样式对象来设置单元格的字体、颜色、边框等属性。 一旦我们完成了Excel文件的创建和数据填充,我们可以通过输出流将其保存为文件或将其发送给用户。可以选择不同的文件格式,如xls或xlsx。 使用POI生成Excel文件非常灵活和强大。我们可以根据自己的需求来添加不同的功能和自定义。可以创建多个Sheet,合并单元格,设置条件格式,添加图等。 总之,POI是一个功能强大的Java库,可以轻松地生成和操作Excel文件。它提供了丰富的API和灵活的操作方式,使我们可以根据自己的需求来创建各种各样的Excel文件。无论是生成、导出数据还是进行数据处理,POI都是一个理想的工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值