簡體   English   中英

如何使用HSSFSheet Apache POI在Excel中創建具有多個樣式的單元格?

[英]How to create cell with multiple styles in excel using HSSFSheet Apache POI?

我正在為excel創建導出文檔的腳本。

如何通過合並幾個單元格來獲得像“ Name: Mark DOB: 11-11-2014”這樣的單元格值?

您需要做的是為您的單元格創建一個RichTextString 這是將不同格式/樣式應用於同一單元格的不同部分以便在Excel中顯示的方法

您需要查看POI“使用富文本”示例 ,了解有關如何使用它的更多信息,但廣泛地說,它將類似於

    Cell cell = row.createCell(1);
    RichTextString rt = new XSSFRichTextString("The quick brown fox");

    Font font1 = wb.createFont();
    font1.setBoldWeight(Font.BOLDWEIGHT_BOLD);
    rt.applyFont(0, 10, font1);

    Font font2 = wb.createFont();
    font2.setItalic(true);
    font2.setUnderline(XSSFFont.U_DOUBLE);
    rt.applyFont(10, 19, font2);

    Font font3 = wb.createFont();
    font3.setBoldWeight(Font.BOLDWEIGHT_NORMAL);
    rt.append(" Jumped over the lazy dog", font3);

    cell.setCellValue(rt);

這應該給你一個粗體,斜體+下划線和正常混合的單元格

我為此創建了一個簡短的完整示例。

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;

import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


class RichTextTest {

 public static void main(String[] args) {
  Workbook wb = new XSSFWorkbook();
  Sheet sheet = wb.createSheet("Sheet1");

  Row row = sheet.createRow(0);

  Cell cell = row.createCell(0);

  RichTextString richString = new XSSFRichTextString( "Name: Mark DOB: 11-11-2014" );
                                                     //^0  ^4     ^11^14
  Font fontBold = wb.createFont();
  //fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD);
  fontBold.setBold(true);

  richString.applyFont( 0, 4, fontBold );
  richString.applyFont( 11, 14, fontBold );
  cell.setCellValue(richString);


  try {
   FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
   wb.write(fileOut);
   fileOut.flush();
   fileOut.close();
  } catch (FileNotFoundException fnfex) {
  } catch (IOException ioex) {
  }

 }
}

有關詳細信息,請參閱文檔

如何創建工作簿,工作表和單元格: http//poi.apache.org/spreadsheet/quick-guide.html#CreateCells

如何使用Richtext: https ://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRichTextString.html

字體界面: https//poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Font.html

你嘗試過使用JXLS嗎?

使用xls模板,您可以從Excel讀取和寫入數據。 它使用起來非常簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM