数据库查询数据简单写入Word,PDF文档

 本文简略创建了两种格式的文件,部分代码需要根据实际业务进行调整,代码中如有错误,望各位大佬多多体谅并提出纠正

maven 依赖

      <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext-rtf</artifactId>
            <version>2.1.7</version>
        </dependency>

创建word

/*
 *List<beanVo> list 传入需要写入的对象集合
 */
    public File toWord(List<beanVo> list, String fileName, String title, HttpServletResponse res, HttpServletRequest request) {
    
    
        Document document = new Document(PageSize.A4);
        try {
    
    
            // 创建文件
            // fileName:url + 文件名称 + .doc
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
    
    
                file.delete();
            }
            file.createNewFile();
            
            // 写入文件信息
            RtfWriter2.getInstance(document, new FileOutputStream(fileName));
            document.open();
            Paragraph ph = new Paragraph();
            Font f = new Font();
            //设置标题
            Paragraph p = new Paragraph(title, new Font(Font.NORMAL, 24, Font.BOLDITALIC, new Color(0, 0, 0)));
            p.setAlignment(1);
            document.add(p);
            ph.setFont(f);
            
            //创建word文档表格共5列
            Table table = new Table(5);
            document.add(new Paragraph(""));
            table.setBorderWidth(1);
            table.setPadding(0);
            table.setSpacing(0);
            //添加表头的元素,并设置表头背景的颜色
            Color chade = new Color(176, 196, 222);
            //第一行列名
            Cell cell = new Cell("序号");
            addWordCell(table, cell, chade);
            cell = new Cell("第一列");
            addWordCell(table, cell, chade);
            cell = new Cell("第二列");
            addWordCell(table, cell, chade);
            cell = new Cell("第三列");
            addWordCell(table, cell, chade);
            cell = new Cell("第四列");
            addWordCell(table, cell, chade);
            table.endHeaders();

            // 表格的主体,每行对应列的数据内容
            for (int i = 0; i < list.size(); i++) {
    
    
                addContent(table, cell, (i + 1) + "");
                addContent(table, cell,list.get(i).getTaskDesc());
                addContent(table, cell, list.get(i).getDepartName());
                addContent(table, cell, list.get(i).getTaskMeasures());
                addContent(table, cell, list.get(i).getContactPerson());
            }
            
            //生成表格
            document.add(table);
            document.close();
            return file;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return  null;
    }


    /**
     *  word添加表头到表格
     */
    private void addWordCell(Table table, Cell cell, Color chade) {
    
    
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(chade);
        table.addCell(cell);
    }

    /**
     * word添加内容到表格
     */
    private void addContent(Table table, Cell cell, String content) {
    
    
        cell = new Cell(content);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
    }

创建pdf

    // 定义全局的字体静态变量
    private static com.itextpdf.text.Font titlefont;
    private static com.itextpdf.text.Font headfont;
    private static com.itextpdf.text.Font keyfont;
    private static com.itextpdf.text.Font textfont;
    // 最大宽度
    private static int maxWidth = 520;
    // 静态代码块
    static {
    
    
        try {
    
    
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new com.itextpdf.text.Font(bfChinese, 16, com.itextpdf.text.Font.BOLD);
            headfont = new com.itextpdf.text.Font(bfChinese, 14, com.itextpdf.text.Font.BOLD);
            keyfont = new com.itextpdf.text.Font(bfChinese, 10, com.itextpdf.text.Font.BOLD);
            textfont = new com.itextpdf.text.Font(bfChinese, 10, com.itextpdf.text.Font.NORMAL);

        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    public File toPDF(List<AccountTaskVo> list, String fileName, String title,HttpServletResponse res, HttpServletRequest request){
    
    
        try {
    
    
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            // fileName:url + 文件名称 + .pdf
            File file = new File(fileName);
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

            // 3.打开文档
            document.open();
            //设置标题
            com.itextpdf.text.Paragraph paragraph = new com.itextpdf.text.Paragraph(title, titlefont);
            paragraph.setAlignment(1); //设置文字居中 0靠左   1,居中     2,靠右
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            paragraph.setLeading(20f); //行间距
            paragraph.setSpacingBefore(5f); //设置段落上空白
            paragraph.setSpacingAfter(10f); //设置段落下空白
            // 直线
            com.itextpdf.text.Paragraph p1 = new com.itextpdf.text.Paragraph();
            p1.add(new com.itextpdf.text.Chunk(new LineSeparator()));
            
            //创建5列
            PdfPTable table = new PdfPTable(5);
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            
            //第一行每列的列明
            table.addCell(createCell("序号", keyfont, Element.ALIGN_CENTER));
            table.addCell(createCell("任务描述", keyfont, Element.ALIGN_CENTER));
            table.addCell(createCell("责任单位", keyfont, Element.ALIGN_CENTER));
            table.addCell(createCell("落实举措", keyfont, Element.ALIGN_CENTER));
            table.addCell(createCell("完成期限", keyfont, Element.ALIGN_CENTER));
            
			//每行对列的数据
            for (int i = 0; i < list.size(); i++) {
    
    
                table.addCell(createCell((i+1)+"", textfont));
                table.addCell(createCell(list.get(i).getTaskDesc(), textfont));
                table.addCell(createCell(list.get(i).getDepartName(), textfont));
                table.addCell(createCell(list.get(i).getTaskMeasures(), textfont));
                table.addCell(createCell(list.get(i).getContactPerson(), textfont));
            }
            
            document.add(paragraph);
            document.add(p1);
            document.add(table);
            // 5.关闭文档
            document.close();
            return file;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    /**
     * PDF创建单元格(指定字体)
     */
    public PdfPCell createCell(String value, Font font) {
    
    
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * PDF创建单元格(指定字体、水平..)
     */
    public PdfPCell createCell(String value, Font font, int align) {
    
    
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * PDF创建指定列宽、列数的表格
     */
    public PdfPTable createTable(float[] widths) {
    
    
        PdfPTable table = new PdfPTable(widths);
        try {
    
    
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return table;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43831522/article/details/112967026