Poi CellType format Cells - java

I've looked arround and have'nt found a answer to my problem.
I try to format a Cell with a custom CellType, does anyone know if it's possible.
I try to use the custom Format '[HH]:MM' on my Cells.
As far as I found out is it only possible to use the predefined CellTypes. Does anyone know more and can halp me?
Thanks in advance

Below is an example of some code which will do what you are trying to achieve.
Workbook w = new XSSFWorkbook();
CreationHelper createHelper = w.getCreationHelper();
CellStyle cs = w.createCellStyle();
cs.setDataFormat(createHelper.createDataFormat().getFormat("HH:mm"));
Sheet sheet = w.createSheet(String.valueOf("Format Test"));
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(cs);
cell.setCellValue(new Date());
File outFile = new File("Test.xlsx");
try {
FileOutputStream fileOut = new FileOutputStream(outFile);
w.write(fileOut);
} catch (IOException ex) {
// do something with exception data
}

Related

In Streaming XSSFWorkbook make part of cell content to bold using apache poi

I am trying following two sets of code to make part of the cell content bold/italic in streaming XSSFWorkbook that is SXSSFWorkbook. But it is not working. Any help in this regard is appreciated.
The cell content should look like following
This is sample content
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
SXSSFSheet sheet = wb.createSheet("With Rich Text");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
XSSFFont fontPlain = (XSSFFont) wb.createFont();
XSSFFont fontBoldItalic = (XSSFFont) wb.createFont();
fontBoldItalic.setBold(true);
fontBoldItalic.setItalic(true);
XSSFFont fontItalic = (XSSFFont) wb.createFont();
fontItalic.setItalic(true);
XSSFRichTextString cell1Value= new XSSFRichTextString();
cell1Value.append("This is ");
cell1Value.append("sample ", fontBoldItalic);
cell1Value.append("content", fontItalic);
cell.setCellValue(cell1Value);
wb.write(new FileOutputStream("BoldFile.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
Also following code does the same. The cell content should look like following
Hello World
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
SXSSFSheet sheet = wb.createSheet("With Rich Text");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
Font fontBold = wb.createFont();
fontBold.setBold(true);
String value = "Hello World";
String subValue = "World";
cell.setCellValue(value);
RichTextString rts = cell.getRichStringCellValue();
rts.applyFont(value.indexOf(subValue), value.length(), fontBold);
cell.setCellValue(rts);
wb.write(new FileOutputStream("BoldFile.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
You should always create the RichTextString using CreationHelper.createRichTextString(java.lang.String text) where CreationHelper comes from Workbook.getCreationHelper(). So you can be sure, that the created RichTextString always is of same type as the workbook. For example HSSFRichTextString from a HSSFCreationHelper, XSSFRichTextString from a XSSFCreationHelper and XSSFRichTextString for streaming SXSSF from a SXSSFCreationHelper. When created using the constructors that is not always guaranteed.
But using SXSSF there is an issue when SXSSFWorkbook uses inline strings instead of a shared strings table. This is the default in SXSSF because inline strings are better usable in the streaming approach. But Apache POI fails to create rich text content in inline strings. It only creates rich text content in the shared strings table, which is the default in Excel.
So using Workbook workbook = new SXSSFWorkbook(); no rich text cell content can be created. One needs using Workbook workbook = new SXSSFWorkbook(new XSSFWorkbook(), 100, false, true); which tells to create a SXSSFWorkbook from a new empty XSSFWorkbook, using the default rowAccessWindowSize of 100, not to use gzip compression for temporary files and to use a shared strings table.
Following code will work for all kinds of Workbook and create rich text cell content.
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelRichTextString {
public static void main(String[] args) throws Exception {
//Workbook workbook = new XSSFWorkbook(); FileOutputStream out = new FileOutputStream("./Excel.xlsx");
//Workbook workbook = new HSSFWorkbook(); FileOutputStream out = new FileOutputStream("./Excel.xls");
//Workbook workbook = new SXSSFWorkbook(); FileOutputStream out = new FileOutputStream("./Excel.xlsx");
Workbook workbook = new SXSSFWorkbook(new XSSFWorkbook(), 100, false, true); FileOutputStream out = new FileOutputStream("./Excel.xlsx");
CreationHelper creationHelper = workbook.getCreationHelper();
Font font = workbook.createFont(); // default font
Font fontBold = workbook.createFont();
fontBold.setBold(true);
Font fontItalic = workbook.createFont();
fontItalic.setItalic(true);
String text = "This is some sample content.";
RichTextString richTextString = creationHelper.createRichTextString(text);
String word = "some";
int startIndex = text.indexOf(word);
int endIndex = startIndex + word.length();
richTextString.applyFont(startIndex, endIndex, fontBold);
word = "sample";
startIndex = text.indexOf(word);
endIndex = startIndex + word.length();
richTextString.applyFont(startIndex, endIndex, fontItalic);
Sheet sheet = workbook.createSheet();
sheet.createRow(0).createCell(0).setCellValue(richTextString);
workbook.write(out);
out.close();
workbook.close();
if (workbook instanceof SXSSFWorkbook) ((SXSSFWorkbook)workbook).dispose();
}
}
Conclusion: Stop thinking SXSSF is the better XSSF because of using streaming approach to save memory usage. It is not. It has disadvantages of it's own. The structure of spreadsheet application files is nothing what is good to stream bulk data in.

Apache POI creating corrupt XLSX files

I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}

CellStyle is applied only upon editing cell

I am using this sample to change the color of a particular cell in the file
InputStream inp = new FileInputStream("C:\\temp\\vineet.xlsx");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
XSSFCellStyle defaultStyle = (XSSFCellStyle) wb.getCellStyleAt((short) 0);
style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");
if (cell.getCellStyle().equals(defaultStyle)) {
cell.setCellStyle(style);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("C:\\temp\\vineet.xlsx");
wb.write(fileOut);
fileOut.close();
at the first glance there are no changes, but when i try to edit the cell value using excel then the cell became yellow-backgrounded.
you already got the needed line to do what you need but you commented it out.
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
and change this:
style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
to
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

Putting result of Java program into Excel cell

I simply want to put the result of a Java program into an Excel cell. Let's assume the result is 5, then my code in main() would look like this:
XSSFWorkbook wb = C:\Users\Username\Desktop\java-programs\results.xlsm;
XSSFSheet ExcelSheet = wb.getSheet("numbers");
XSSFRow row = ExcelSheet.getRow(0);
XSSFCell cell = row.getCell(0);
cell.setCellValue(5);
However, this code doesn't compile.
I read some examples on this topic but the code given simply refers to the Excel sheet as (e.g.) "sheet" and then goes on with sheet.getRow(some number). The examples don't explain how I tell Java which workbook to write to.
Your first line is incorrect.. try this:
String fileName = "C:/Users/Username/Desktop/java-programs/results.xlsm";
FileInputStream fileIn = new FileInputStream(fileName);
Workbook wb = WorkbookFactory.create(fileIn);
// update the workbook
wb.getSheet("numbers").getRow(0).getCell(0).setCellValue(5);
fileIn.close();
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.close();

Number stored as text warning in excel using POI

I am getting Number stored as text warning for the created excel file using POI. I am trying to display percentage. This question discusses the same, but it's for python. Can some one please suggest me how to avoid this in java using POI?
Below are the lines where I get this warning.
workbook= new XSSFWorkbook();
sh1 = wb.createSheet("Data Sheet");
cell = row.createCell(3);
cell.setCellValue(37 + "%");
Based on Gagravarr answer I did it this way.
XSSFDataFormat df = workbook.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
But it just shows up as 0.37 with no warning now, not 37%.
You're getting the warning because, as it says, you're storing a number as text.
What you probably want to do is:
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
That will store the number 37 as a number, and tell excel to apply a percentage format string to it. Oh, and since 37% is 0.37, you need to store 0.37 not 37!
Edit By popular request, here's a standalone program you can use to see it in action, for both .xls and .xlsx files. Tested with POI 3.10 final, and with all the required dependencies and component jars on the classpath.
public class TestPercent {
public static void main(String[] args) throws Exception {
System.out.println("Generating...");
for (Workbook wb : new Workbook[] {new HSSFWorkbook(), new XSSFWorkbook()}) {
Sheet sheet = wb.createSheet("Data Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(3);
DataFormat df = wb.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
String output = "/tmp/text.xls";
if (wb instanceof XSSFWorkbook) { output += "x"; }
FileOutputStream out = new FileOutputStream(output);
wb.write(out);
out.close();
}
System.out.println("Done");
}
}
Try also setting the CellType:
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
if(NumberUtils.isDigits(text)){
titleCell.setCellValue(Integer.parseInt(text));
}else{
titleCell.setCellValue(text);
}
XSSFWorkbook xSSFWorkbook = new XSSFWorkbook();
CreationHelper createHelper = xSSFWorkbook.getCreationHelper();
XSSFCellStyle numberStyle = xSSFWorkbook.createCellStyle();
numberStyle.setDataFormat(createHelper.createDataFormat().getFormat("###.00"));
double d = 50.0;
XSSFRow dataRow = sheet.createRow(1);
Cellcel1 = dataRow.createCell(1);
cel1.setCellValue(d);
This may be a bit old but try this:
df.getFormat("0.00%")

Categories