I'm trying to set the colunm width with setColumnWidth(rowindex, width) using POI,problem is the width is in double and the function above only accept Int
I tried using autosizecolumn but its still living underpopulated space in the column, problem i think is the font mismatch between excel and java
code
RowTotal = NewSheet.createRow(0);
cell1 = RowTotal.createCell(0);
cell1.setCellValue("Row Name/Label");
cell1 = RowTotal.createCell(1);
cell1.setCellValue("Sum of premium payable");
cell1 = RowTotal.createCell(2);
cell1.setCellValue("Sum of arrears payable");
NewSheet.setColumnWidth(0, 3755.84);
NewSheet.setColumnWidth(1, 5519.68);;
NewSheet.setColumnWidth(2, 5207.36);
You cannot pass double value to setColumnWidth as well as to autosizecolumn because both the methods of Apache POI accepts int value as parameters.
Methods of Apache POI:
1. autoSizeColumn(int column)
Adjusts the column width to fit the contents.
2. setColumnWidth(int columnIndex, int width)
Set the width (in units of 1/256th of a character width)
you can refer to https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html
for more details.
Use:
NewSheet.getColumnHelper().setColWidth(0, 3755.84);
NewSheet.getColumnHelper().setCustomWidth(0, true);
I'm not sure if the second line is necessary but if you manually change the width of a column in excel, it will automatically set CustomWidth = true. So I just add it to be safe.
Related
I have a function which I've been using for a good while in java which calculates cell widths for a pdftable from a given array of string values.
It works very well, and I recently wrote a version of the function in c# and it doesn't give the expected result (i.e text is wrapped to multiple lines) - both java and c# code shown below any help much appreciated
This is the Java version;
float[] CalculateCellWidths(String[] CellHeaders, Font CellFont)
{
float[] CellWidths = new float[CellHeaders.length];
for (int i = 0; i < CellHeaders.length; i++)
{
CellWidths[i] = CellFont.getCalculatedBaseFont(true).getWidthPoint(CellHeaders[i], CellFont.getCalculatedSize());
}
return CellWidths;
}
This is the C# version;
float[] CalculateCellWidths(String[] CellHeaders, iTextSharp.text.Font CellFont)
{
float[] CellWidths = new float[CellHeaders.Length];
for (int i = 0; i < CellHeaders.Length; i++)
{
CellWidths[i] = CellFont.GetCalculatedBaseFont(true).GetWidthPoint(CellHeaders[i], CellFont.CalculatedSize);
}
return CellWidths;
}
I see from your comment that the problem has been solved, but that you don't know why, so here's a small explanation about LockWidth.
There are two ways to define the width of a table. Either the table takes a percentage of the available width. This is a relative width that depends on page size and page margins. Historically, this percentage is 80% and the table is centered. You can change this width percentage with the setWidthPercentage() method. If you use a method to set the widths of the invidual columns, those widths will be treated as relative widths, for instance { 10, 10, 20 } means that you have a table with 3 columns where the first two columns take a quarter of the available width and the third column takes half.
You can also set the absolute width of a table. You can set the total width with the setTotalWidth() method. You can also define the absolute widths of the columns. However, these absolute widths are ignored in favor of the default width percentage as long as you don't "lock" the width. This is what happens if you use setLockedWidth(true) (Java) or table.LockedWidth = true (C#).
Based on your comment, I think the problem was caused by locking the width of the columns so that absolute values were used instead of relative values.
How to set width for cell? I tried trough cell properties, but it does not work
private void addTableCell(Tr tableRow, String content, boolean setWidth, int width) {
Tc tableCell = factory.createTc();
if (setWidth) {
setCellWidth(tableCell, width);
}
tableCell.getContent().add(
wordMLPackage.getMainDocumentPart().
createParagraphOfText(content));
tableRow.getContent().add(tableCell);
}
private void setCellWidth(Tc tableCell, int width) {
TcPr tableCellProperties = new TcPr();
TblWidth tableWidth = new TblWidth();
tableWidth.setW(BigInteger.valueOf(width));
tableCellProperties.setTcW(tableWidth);
tableCell.setTcPr(tableCellProperties);
}
You should also set w:tbl/w:tblGrid; see further ecma376/WordML/Tables
The easiest way to set things appropriately is to make a table to your liking in Word, then generate corresponding code from that using the docx4j webapp, or the Docx4jHelper Word AddIn.
For more on w:tcW, see the spec.
It's possible you need to set the width type for the cell. Try adding
tableWidth.setType("dxa");
before calling setTcW() in your setCellWidth function.
I'm having some issues with autosizing cells. After my program populates and formats each accordingly, it autosizes the cells to make it look visually acceptable. The issue is, when the cell is formatted as percentage, it auto-sizes the cell without taking in consideration the fact that there's a '%' character, so we end up getting #### on the cells until you expand the cell. Is there a way to autosize it WHILE taking in consideration that extra '%' character?
EDIT:
So this is what happens, the left VAR has been autosized correctly for whatever reasons, but the VAR on the right hasn't.
EDIT2:
I noticed that this ONLY happens when the cell value is 0.00% So all the values in the column for VAR that has #### were 0s and some of the values in the left column for VAR were non-zeros.
While this may not be an ideal solution, one possibility is to grab the size of the string you are inserting into the cell (ie. "50.00%" = size of 6), and set the cell width based manually based on that.
I'm afraid this is not supported in Apache POI, as it disregards the custom cell formatting when trying to calculate column width (it only takes font characteristics and rotation into consideration, but no DataFormat).
As a workaround you can try to write your custom autoSizeColumn method as a modification of the one currently implemented, i.e.:
public void autoSizeColumn(Sheet sheet, int column, int plusMinusChars) {
double width = SheetUtil.getColumnWidth(sheet, column, false);
if (width != -1) {
width += plusMinusChars;
width *= 256;
int maxColumnWidth = 255*256; // The maximum column width for an individual cell is 255 characters
if (width > maxColumnWidth) {
width = maxColumnWidth;
}
sheet.setColumnWidth(column, (int)(width));
}
}
Then you can call it with an extra '%' character to be printed out:
//4th column autosized + 1 character in width to accomodate for '%'
autoSizeColumn(sheet, 3, 1);
How to get height and width of excel sheet named range area from HSSFWorkbook POI API.
I got one reference from google but not able to get height and width of named index area of excel sheet.
Thanks in advance.
Yes it's named range, and want height and width of cells aquired by named range. below code having "print_area" named range and want to height and width of cells.
int namedCellIdx = workbook.getNameIndex("Print_Area");
HSSFName aNamedCell = workbook.getNameAt(namedCellIdx);
// retrieve the cell at the named range and test its contents
String a = aNamedCell.getReference();
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
Sheet s = workbook.getSheet(crefs[i].getSheetName());
Row r = sheet.getRow(crefs[i].getRow());
System.out.println(r.getHeight());
System.out.println(sheet.getColumnWidth(crefs[i].getCol()));;
//here want height and width of "Print_area" cells
Cell c = r.getCell(crefs[i].getCol());
System.out.println(c.getStringCellValue());
// extract the cell contents based on cell type etc.
}
Read the API docs at http://poi.apache.org/apidocs/index.html
Specifically, look at org.apache.poi.ss.util.AreaReference, from which you can get the first and last cell references and determine the size of the range.
However, you have to cope with a number of special cases, such as areas that are an entire column or entire row, or even non-contiguous.
I want to increase the width of the column of excel sheet. as the i am writing trough code is long.
and I need to drag the column manually to see the full text.
I did this –
HSSFRow dataRow = sampleDataSheet.createRow(0);
HSSFCellStyle cellStyle = setHeaderStyle(sampleWorkbook);
cellStyle.setWrapText(true);
***sampleDataSheet.autoSizeColumn(1000000);***
But its not changing anything..
This should work. However,
sampleDataSheet.autoSizeColumn(1000000);
auto-expands column 1000000.
If you want to auto-expand column 0(the first column), use:
sampleDataSheet.autoSizeColumn(0);
To auto-expand column 0 to 9(the first 10 columns):
for (int i=0; i<10; i++){
sampleDataSheet.autoSizeColumn(i);
}
Also, you should create all your rows and fill them with content first, before you call autoSizeColumn(so the column gets the width of the value with the broadest width).
(If you want to set the column width to a fixed value, use HSSFSheet.setColumnWidth(int,int) instead.)
// We can set column width for each cell in the sheet
sheet.setColumnWidth(0, 1000);
sheet.setColumnWidth(1, 7500);
sheet.setColumnWidth(2, 7500);
// By applying style for cells we can see the total text in the cell for specified width
HSSFCellStyle cellStyle = workBook.createCellStyle();
cell.setCellStyle(cellStyle );
cellStyle.setWrapText(true);
sheet.autoSizeColumn(columnNumber) works. this will resize the column to the largest cell length.