Apache-poi:自动设置合并单元格的大小并使字体变为粗体

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Apache-poi:自动设置合并单元格的大小并使字体变为粗体相关的知识,希望对你有一定的参考价值。

我对此并不陌生,只是与apache-poi一起玩以生成带有一些模拟数据的excel工作表,这是我的课程,我不知所措,没有任何最佳实践?? enter image description here

  1. 自动设置行的大小,并合并行中的单元格。
  2. 字体粗体->对于第一行中的所有单元格。

class:

package com.example.TestProject.process;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class WriteExcelDemo 

    public static void main(
            String[] args) 

        // Blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Employee Data");

        // This data needs to be written (Object[])
        Map<String, Object[]> data = new TreeMap<String, Object[]>();
        data.put("1", new Object[] "ID", "NAME", "LASTNAME");
        data.put("2", new Object[] 1, "Amit", "Shukla");
        data.put("3", new Object[] 2, "Lokesh", "Gupta");
        data.put("4", new Object[] 3, "John", "Adwards");
        data.put("5", new Object[] 4, "Brian", "Schultz");

        // Iterate over data and write to sheet
        Set<String> keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset) 
            Row row = sheet.createRow(rownum++);
            Object[] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr) 
                Cell cell = row.createCell(cellnum++);
                if (obj instanceof String)
                    cell.setCellValue((String) obj);
                else if (obj instanceof Integer)
                    cell.setCellValue((Integer) obj);
            
        
        try 
            // Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx"));
            workbook.write(out);
            out.close();

            System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");

         catch (Exception e) 
            e.printStackTrace();
        
    

答案

用于自动调整列的值为Sheet.autoSizeColumn。您可以指定是否应考虑合并单元格的内容。默认为忽略合并的单元格。但是由于您的代码根本没有合并单元格,因此您的问题目前还不清楚。

对于行样式,有Row.setRowStyle。当新单元格添加到该行时,Excel采用该样式。但是apache poi的行为不像这样。对于新创建的单元格,它始终使用默认的单元格样式。因此,我们需要一种方法CellStyle getPreferredCellStyle(Cell cell)来获取给定单元格的首选单元格样式,就像Excel那样。

而且,由于您正在询问最佳实践,因此请尽可能使用org.apache.poi.ss.usermodel.*。因此,代码可以处理HSSFXSSF而无需做太多更改。

示例:

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class WriteExcelDemo 

 static CellStyle getPreferredCellStyle(Cell cell) 
  // a method to get the preferred cell style for a cell
  // this is either the already applied cell style
  // or if that not present, then the row style (default cell style for this row)
  // or if that not present, then the column style (default cell style for this column)
  CellStyle cellStyle = cell.getCellStyle();
  if ((cell instanceof XSSFCell && cellStyle.getIndex() == 0) || (cell instanceof HSSFCell && cellStyle.getIndex() == 15)) cellStyle = cell.getRow().getRowStyle();
  if (cellStyle == null) cellStyle = cell.getSheet().getColumnStyle(cell.getColumnIndex());
  if (cellStyle == null) cellStyle = cell.getCellStyle();
  return cellStyle;
 

 public static void main(String[] args) throws Exception 

  // Blank workbook XSSF or HSSF
  Workbook workbook = new XSSFWorkbook();
  //Workbook workbook = new HSSFWorkbook();

  // Create needed cell styles on workbook level
  Font boldFont = workbook.createFont();
  boldFont.setBold(true);
  CellStyle headerRowStyle = workbook.createCellStyle();
  headerRowStyle.setFont(boldFont);


  // This data needs to be written (Object[])
  Map<String, Object[]> data = new TreeMap<String, Object[]>();
  data.put("1", new Object[] "ID", "NAME", "LASTNAME");
  data.put("2", new Object[] 1, "Amit", "Shukla");
  data.put("3", new Object[] 2, "Lokesh", "Gupta");
  data.put("4", new Object[] 3, "John", "Adwards");
  data.put("5", new Object[] 4, "Brian", "Schultz");

  // Create a blank sheet
  Sheet sheet = workbook.createSheet("Employee Data");

  // Iterate over data and write to sheet
  Set<String> keyset = data.keySet();
  int rownum = 0;
  for (String key : keyset) 
   Row row = sheet.createRow(rownum++);
   if (rownum == 1) row.setRowStyle(headerRowStyle); // row style for first row; Excel takes that style when new cells are added to this row
   Object[] objArr = data.get(key);
   int cellnum = 0;
   for (Object obj : objArr) 
    Cell cell = row.createCell(cellnum++);
    cell.setCellStyle(getPreferredCellStyle(cell)); // set the preferred cell style for the new cell as Excel would do
    if (obj instanceof String)
     cell.setCellValue((String) obj);
    else if (obj instanceof Integer)
     cell.setCellValue((Integer) obj);
   
  

  for (int c = 0; c < data.get("1").length; c++) 
   //sheet.autoSizeColumn(c); // autosize, merged cells should be ignored
   sheet.autoSizeColumn(c, true); // autosize, merged cells should be considered
  

  // Write the workbook in file system
  String filepath = (workbook instanceof XSSFWorkbook)?"./howtodoinjava_demo.xlsx":"./howtodoinjava_demo.xls";
  FileOutputStream out = new FileOutputStream(new File(filepath));
  workbook.write(out);
  out.close();
  workbook.close();

  System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
 

以上是关于Apache-poi:自动设置合并单元格的大小并使字体变为粗体的主要内容,如果未能解决你的问题,请参考以下文章

如何通过自动布局设置集合视图单元格大小

合并单元格的快捷键

自动调整大小(动态高度)表格视图单元格的问题

具有动态大小的单元格的复杂自动布局

Excel表怎么让单元格自动调整宽度?

html中表格设定的长和宽,为啥还会随着内容改变大小