How to create a cell with several styles in excell using HSSFSheet Apache POI?

I am creating a script to export a document as excel. I found some difficulties in that: I want the cell value to be " Name: Mark DOB: 11-11-2014" by merging several cells. Can you help me solve this problem?

Thanks in advance!

+4
source share
3 answers

What you need to do is create a RichTextString for your cell. This is a way to apply different formatting / styles for different parts of the same cell for display in 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);

, +

+8

.

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

+6

JXLS?

Using xls templates, you can read and write data from Excel. Its very easy to use.

0
source

All Articles