使用poi导出固定excel的模板,出现汉字不能自动设置行宽

因为在工作中,可能因为不同的原因遇到不同的问题,本人就分享遇到的一个大坑

因为我要将数据库中的一部分字段的名称作为Excel中的列名,所以需要导出汉字,然后在对应的汉字下面填充数据.

正是因为这部分汉字,在使用的过程中.导出的表格,所有的汉字都挤在了一起,

并没有达到我们想要的效果所以我在这里进行了以下设置:

引入的依赖为:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

测试的代码为:

package exercise.demo;

import org.apache.poi.hssf.usermodel.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.FileOutputStream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Test
    public  void excelUtils() {
        /**
         * @see <a href="http://poi.apache.org/hssf/quick-guide.html#NewWorkbook">For more</a>
         */
        // 创建新的Excel 工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
        HSSFSheet sheet = workbook.createSheet();
        //HSSFSheet sheet = workbook.createSheet("SheetName");

        // 用于格式化单元格的数据
        HSSFDataFormat format = workbook.createDataFormat();

        // 创建新行(row),并将单元格(cell)放入其中. 行号从0开始计算.
        HSSFRow row = sheet.createRow((short) 1);

        // 设置字体
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 20); //字体高度
        font.setColor(HSSFFont.COLOR_RED); //字体颜色
        font.setFontName("黑体"); //字体
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度
        font.setItalic(true); //是否使用斜体
//        font.setStrikeout(true); //是否使用划线

        // 设置单元格类型
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
        cellStyle.setWrapText(true);

        // 添加单元格注释
        // 创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
        HSSFPatriarch patr = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        HSSFComment comment = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
        // 设置注释作者. 当鼠标移动到单元格上是可以在状态栏中看到该内容.
        comment.setAuthor("Xuys.");

//        // 创建单元格
        HSSFCell cell = row.createCell((short) 1);
        String[] columMethodNms = new String[]{"*户主姓名", "*门牌号"};

        for (int j = 0; j < columMethodNms.length; j++) {
            cell = row.createCell(j);
//            cell.setCellStyle();
            cell.setCellValue(columMethodNms[j]);

这里这部分代码可以改变汉字的行宽
sheet.setColumnWidth(j,columMethodNms[j].getBytes().length
*256); } try { FileOutputStream fileOut = new FileOutputStream("G:/3.xls"); workbook.write(fileOut); fileOut.close(); } catch (Exception e) { System.out.println(e.toString()); } } }

这部分代码经过本人测试,是可以正常运行工的.

或者你也试试将这个方法引入到这个类中.

 private static void reformatSheetWidth(XSSFSheet sheet, String[] columMethodNms) {
        for (int columnNum = 0; columnNum < columMethodNms.length; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                XSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
                    XSSFCell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

这两个方法都可以用来进行测试,本人在项目中用过这样的方法.

posted @ 2019-08-01 23:40  King-DA  阅读(325)  评论(0编辑  收藏  举报