Hey all I am trying to get my cell to vertical line instead of just being aligned by the left side using POI.
This is my java code:
static CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
Row headerRow = null;
sheet = workbook.createSheet("String " + sheetname);
headerCellStyle.setWrapText(true);
headerCellStyle.setAlignment(HorizontalAlignment.LEFT);
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE);
// Create a Row
headerRow = sheet.createRow(0);
However, the line headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE); has an error of:
The method setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment) in the type CellStyle is not applicable for the arguments (org.apache.poi.sl.usermodel.VerticalAlignment)
How can i go about getting this to work if I have already defined it as an static CellStyle headerCellStyle = workbook.createCellStyle();?
Changing to SS does not seem to have the "middle" option?
This is the difference within excel for those 2 types:
The default way:
The Middle way (the way I am wanting):
The Center way:
Your second image (the way you want) shows CellStyle.setVerticalAlignment(VerticalAlignment.CENTER). Your third image shows CellStyle.setAlignment(HorizontalAlignment.CENTER).
There is a difference between setVerticalAlignment(VerticalAlignment.CENTER) and setAlignment(HorizontalAlignment.CENTER). The first sets vertical alignment to center (aka middle). The second sets horizontal alignment to center.
Complete Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelVerticalAlignment {
public static void main(String[] args) throws Exception {
// try (Workbook workbook = new XSSFWorkbook();
// FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {
try (Workbook workbook = new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("Excel.xls") ) {
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Sheet sheet = workbook.createSheet();
sheet.setColumnWidth(0, 20*256);
Row row = sheet.createRow(0);
row.setHeightInPoints(40);
Cell cell = row.createCell(0);
cell.setCellStyle(headerCellStyle);
cell.setCellValue("1082192560 1868");
workbook.write(fileout);
}
}
}
Result:
Related
I'm trying to copy from cells from one workbook to another with the latest version of Apache POI (4.1.2).
If both workbooks are .xlsx files, everything works fine. But if the source workbook is an (old) .xls file and the destination workbook is an .xlsx file, the following code fails
// Copy style from old cell and apply to new cell
CellStyle newCellStyle = targetWorkbook.createCellStyle();
newCellStyle.cloneStyleFrom(sourceCell.getCellStyle());
targetCell.setCellStyle(newCellStyle);
The exception that's thrown is:
java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle
If we can't use cloneStyleFrom when the files (or Workbook objects) are of different types, how can we convert a HSSFCellStyle object to a XSSFCellStyle?
The answer to your question "How can we convert a HSSFCellStyle object to a XSSFCellStyle?" is: We can't do that using apache poi 4.1.2. This simply is not supported as clearly stated in CellStyle.cloneStyleFrom: "However, both of the CellStyles will need to be of the same type (HSSFCellStyle or XSSFCellStyle)."
The other question is: Should we at all convert one cell style into another? Or what use cases are there for CellStyle.cloneStyleFrom at all? In my opinion there are none. There are Excel limitations for the count of unique cell formats/cell styles. See Excel specifications and limits. So we should not create a single cell style for each single cell because then those limitations will be reached very fast. So instead of cloning cell styles we should get the style properties from source style style1 and then using CellUtil.setCellStyleProperties to set those style properties to the other cell in question. This method attempts to find an existing CellStyle that matches the cell's current style plus styles properties in properties. A new style only is created if the workbook does not contain a matching style.
Since your question title is "Copy cells between Excel workbooks with Apache POI", I have created a working draft of how I woud do this.
The following code first gets a existent Workbook.xls as HSSFWorkbook wb1 and creates a new XSSFWorkbook wb2. Then it loops over all cells of the first sheet of wb1 and tries copying those cells into the first sheet of wb2. To do so there is a method copyCells(Cell cell1, Cell cell2) which uses copyStyles(Cell cell1, Cell cell2). The latter gets the style properties from source style style1 got from cell1 and then uses CellUtil.setCellStyleProperties to set those style properties to cell2. For copying fonts copyFont(Font font1, Workbook wb2) is used. This tries creating new fonts in wb2 only if such a font is not already present in that workbook. This is necessary because there also is a limit of unique font types per workbook in Excel.
Working example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellUtil;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
class ExcelCopyCells {
static Font copyFont(Font font1, Workbook wb2) {
boolean isBold = font1.getBold();
short color = font1.getColor();
short fontHeight = font1.getFontHeight();
String fontName = font1.getFontName();
boolean isItalic = font1.getItalic();
boolean isStrikeout = font1.getStrikeout();
short typeOffset = font1.getTypeOffset();
byte underline = font1.getUnderline();
Font font2 = wb2.findFont(isBold, color, fontHeight, fontName, isItalic, isStrikeout, typeOffset, underline);
if (font2 == null) {
font2 = wb2.createFont();
font2.setBold(isBold);
font2.setColor(color);
font2.setFontHeight(fontHeight);
font2.setFontName(fontName);
font2.setItalic(isItalic);
font2.setStrikeout(isStrikeout);
font2.setTypeOffset(typeOffset);
font2.setUnderline(underline);
}
return font2;
}
static void copyStyles(Cell cell1, Cell cell2) {
CellStyle style1 = cell1.getCellStyle();
Map<String, Object> properties = new HashMap<String, Object>();
//CellUtil.DATA_FORMAT
short dataFormat1 = style1.getDataFormat();
if (BuiltinFormats.getBuiltinFormat(dataFormat1) == null) {
String formatString1 = style1.getDataFormatString();
DataFormat format2 = cell2.getSheet().getWorkbook().createDataFormat();
dataFormat1 = format2.getFormat(formatString1);
}
properties.put(CellUtil.DATA_FORMAT, dataFormat1);
//CellUtil.FILL_PATTERN
//CellUtil.FILL_FOREGROUND_COLOR
FillPatternType fillPattern = style1.getFillPattern();
short fillForegroundColor = style1.getFillForegroundColor(); //gets only indexed colors, no custom HSSF or XSSF colors
properties.put(CellUtil.FILL_PATTERN, fillPattern);
properties.put(CellUtil.FILL_FOREGROUND_COLOR, fillForegroundColor);
//CellUtil.FONT
Font font1 = cell1.getSheet().getWorkbook().getFontAt(style1.getFontIndexAsInt());
Font font2 = copyFont(font1, cell2.getSheet().getWorkbook());
properties.put(CellUtil.FONT, font2.getIndexAsInt());
//BORDERS
BorderStyle borderStyle = null;
short borderColor = -1;
//CellUtil.BORDER_LEFT
//CellUtil.LEFT_BORDER_COLOR
borderStyle = style1.getBorderLeft();
properties.put(CellUtil.BORDER_LEFT, borderStyle);
borderColor = style1.getLeftBorderColor();
properties.put(CellUtil.LEFT_BORDER_COLOR, borderColor);
//CellUtil.BORDER_RIGHT
//CellUtil.RIGHT_BORDER_COLOR
borderStyle = style1.getBorderRight();
properties.put(CellUtil.BORDER_RIGHT, borderStyle);
borderColor = style1.getRightBorderColor();
properties.put(CellUtil.RIGHT_BORDER_COLOR, borderColor);
//CellUtil.BORDER_TOP
//CellUtil.TOP_BORDER_COLOR
borderStyle = style1.getBorderTop();
properties.put(CellUtil.BORDER_TOP, borderStyle);
borderColor = style1.getTopBorderColor();
properties.put(CellUtil.TOP_BORDER_COLOR, borderColor);
//CellUtil.BORDER_BOTTOM
//CellUtil.BOTTOM_BORDER_COLOR
borderStyle = style1.getBorderBottom();
properties.put(CellUtil.BORDER_BOTTOM, borderStyle);
borderColor = style1.getBottomBorderColor();
properties.put(CellUtil.BOTTOM_BORDER_COLOR, borderColor);
CellUtil.setCellStyleProperties(cell2, properties);
}
static void copyCells(Cell cell1, Cell cell2) {
switch (cell1.getCellType()) {
case STRING:
/*
//TODO: copy HSSFRichTextString to XSSFRichTextString
RichTextString rtString1 = cell1.getRichStringCellValue();
cell2.setCellValue(rtString1); // this fails if cell2 is XSSF and rtString1 is HSSF
*/
String string1 = cell1.getStringCellValue();
cell2.setCellValue(string1);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell1)) {
Date date1 = cell1.getDateCellValue();
cell2.setCellValue(date1);
} else {
double cellValue1 = cell1.getNumericCellValue();
cell2.setCellValue(cellValue1);
}
break;
case FORMULA:
String formula1 = cell1.getCellFormula();
cell2.setCellFormula(formula1);
break;
//case : //TODO: further cell types
}
copyStyles(cell1, cell2);
}
public static void main(String[] args) throws Exception {
Workbook wb1 = WorkbookFactory.create(new FileInputStream("Workbook.xls"));
Workbook wb2 = new XSSFWorkbook();
Sheet sheet1 = wb1.getSheetAt(0);
Sheet sheet2 = wb2.createSheet();
Set<Integer> columns = new HashSet<Integer>();
Row row2 = null;
Cell cell2 = null;
for (Row row1 : sheet1) {
row2 = sheet2.createRow(row1.getRowNum());
for (Cell cell1 : row1) {
columns.add(cell1.getColumnIndex());
cell2 = row2.createCell(cell1.getColumnIndex());
copyCells(cell1, cell2);
}
}
wb1.close();
for (Integer column : columns) {
sheet2.autoSizeColumn(column);
}
FileOutputStream out = new FileOutputStream("Workbook.xlsx");
wb2.write(out);
out.close();
wb2.close();
}
}
If Workbook.xls looks like this:
then the resulting Workbook.xlsx looks like this:
Note: This is a working draft and needs to be completed. See TODO comments in the code. RichTextString cell values needs to be considered. Further cell types needs to be considered.
Method copyStyles only provides copying data format, fill pattern and fill foreground color (only for indexed colors), font and borders. Further cell style properties needs to be considered.
Please note: I see a very similar question asked here but that answer was not very conclusive (I can't discern what the actual fix is/was). If someone can explain to me how that question/answer addresses my present issue at hand, I will happily delete this question myself! Just please don't DV/CV as a "dupe", and instead please help me make sense of that provided solution!
Java 8 and POI 4.1.x here. I am trying to write some Java/POI code that will produce a styled/formatted Excel file as output. I have created this GitHub project that perfectly reproduces the issue I'm seeing. If you really want, you can take a look at it and run it (its a Swing app) via ./gradlew clean build shadowJar && java -jar build/libs/hello-windows.jar, but the TLDR; of it is:
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("SOME_SHEET");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(headerFont);
cellStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setAlignment(HorizontalAlignment.CENTER);
int rowNum = 0;
Row headerRow = sheet.createRow(rowNum);
headerRow.setRowStyle(cellStyle);
Cell partNumberHeaderCell = headerRow.createCell(0);
partNumberHeaderCell.setCellValue("Part #");
partNumberHeaderCell.setCellStyle(cellStyle);
Cell partDescriptionHeaderCell = headerRow.createCell(1);
partDescriptionHeaderCell.setCellStyle(cellStyle);
partDescriptionHeaderCell.setCellValue("Description");
Cell partPriceHeaderCell = headerRow.createCell(2);
partPriceHeaderCell.setCellStyle(cellStyle);
partPriceHeaderCell.setCellValue("Price");
Cell manufacturerHeaderCell = headerRow.createCell(3);
manufacturerHeaderCell.setCellStyle(cellStyle);
manufacturerHeaderCell.setCellValue("Make");
rowNum++;
Row nextRow = sheet.createRow(rowNum);
nextRow.createCell(0).setCellValue(uuid);
nextRow.createCell(1).setCellValue("Some Part");
nextRow.createCell(2).setCellValue(2.99);
nextRow.createCell(3).setCellValue("ACME");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("acme.xlsx");
workbook.write(fos);
workbook.close();
} catch (IOException ex) {
log.error(ExceptionUtils.getStackTrace(ex));
}
When this code runs it produces an Excel file that contains all my data (the header row and a "data" row) correctly, however all the formatting and cell styling seems to be ignored:
In the screenshot above, you can see that the header is not styled at all, however I believe I am styling it correctly:
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(headerFont);
cellStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setAlignment(HorizontalAlignment.CENTER);
If my code is correct then I should see a header that:
Has a yellow background; and
Is horizontally-centered/aligned; and
Is bolded
Can anyone spot where I'm going awry?
Not clear why the bold font not gets applied for you, for me it gets.
But the problem with the cell interior is that Excel cell interiors have pattern fills. There the fill background color is the color behind the pattern and the fill foreground color is the color of the pattern. Solid filled cell interiors must have solid pattern having the needed fill foreground color set.
See also Busy Developers' Guide to HSSF and XSSF Features.
...
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(headerFont);
//cellStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
...
Let's have a complete example which will store your data in an Excel sheet:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class CreateExcelCellStyle {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {
Font headerFont = workbook.createFont();
headerFont.setBold(true);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFont(headerFont);
headerStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
Object[][] data = new Object[][] {
new Object[] {"Part #", "Description", "Price", "Make"},
new Object[] {"cb82c02", "Some Part", 2.99, "ACME"}
};
Sheet sheet = workbook.createSheet();
for (int r = 0; r < data.length; r++) {
Row row = sheet.createRow(r);
for (int c = 0; c < data[0].length; c++) {
Cell cell = row.createCell(c);
if (r==0) cell.setCellStyle(headerStyle);
Object content = data[r][c];
if (content instanceof String) {
cell.setCellValue((String)content);
} else if (content instanceof Double) {
cell.setCellValue((Double)content);
}
}
}
for (int c = 0; c < data[0].length; c++) {
sheet.autoSizeColumn(c);
}
workbook.write(fileout);
}
}
}
Result:
I use Apache POI 3.16 to create an Excel file. I want to set the data inside a particular cell to have a linebreak :
rowConsommationEtRealisation.createCell(0).setCellValue("Consommation (crédits)\r\nRéalisation (produits)");
When I open the file then the cell value does not have linebreak ! So how to create linebreak ?
Try this: here
Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
It has the line break already but the cell does not show it. You need setting a cell style having wrap text property set to the cell.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
class ExcelLineBreakWrapText {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
CellStyle wrapStyle = workbook.createCellStyle();
wrapStyle.setWrapText(true);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(wrapStyle);
cell.setCellValue("Consommation (crédits)\r\nRéalisation (produits)");
sheet.autoSizeColumn(0);
workbook.write(new FileOutputStream("ExcelLineBreakWrapText.xlsx"));
workbook.close();
}
}
Following is my code:
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy",java.util.Locale.ENGLISH);
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
XSSFCellStyle cellStyle = (XSSFCellStyle)updateDateCell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MMM-yy"));
Date updateDate = sdf.parse(monthEndDate);
updateDateCell.setCellValue(updateDate);
updateDateCell.setCellStyle(cellStyle);
It is setting numeric value 43100.0
I suspect your problem is that you are getting the CellStyle via Cell.getCellStyle and then you are overwriting that CellStyle.
CellStyles are in Excel defined on Workbook level. That means, not each cell has it's own cell style but cells share cell styles defined on workbook level.
So if you do the getting the CellStyle via Cell.getCellStyle and then overwriting that CellStyle multiple times then only the last overwriting will be active. So I suspect, your complete code overwrites the same cell style, gotten from another cell, with another number format after you have overwritten it with the date number format.
The easy conclusion could be to really give each cell it's own cell style. But this is also wrong since there is a limit number of cell styles in a workbook. So we need
Having as much own cell styles as needed.
Having as much cell styles shared as possible.
To achieve this CellUtil can be used in apache poi. This provides methods only to create a new cell style if there is not already the same cell style defined in the workbook and simply to use that cell style if there is already the same cell style defined in the workbook.
Example:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class ExcelSetDateValue {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelTest.xlsx"));
//possiby we need data formats
DataFormat dataFormat = wb.createDataFormat();
//get sheet and set row number
XSSFSheet sheet = wb.getSheetAt(0);
int rownumber = 3;
//get the date
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", java.util.Locale.ENGLISH);
Date updateDate = sdf.parse(monthEndDate);
//set date as cell value
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
updateDateCell.setCellValue(updateDate);
//use CellUtil to set the CellStyleProperties
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(CellUtil.DATA_FORMAT, dataFormat.getFormat("dd-MMM-yy"));
CellUtil.setCellStyleProperties(updateDateCell, properties);
wb.write(new FileOutputStream("ExcelTestNew.xlsx"));
wb.close();
}
}
Add updateDateCell = Format(updateDateCell, "dd-MMM-yyyy") at the end of your code.
You should get 31-Dec-2017.
This is an example which I already have for formatting date, you can reuse the part of it ( I marked the relevant lines of code). It's tested and working fine, if any issue let me know.
//UPDATE
Please see Axel Richter's answer https://stackoverflow.com/a/47920182/1053496 for the correct answer. In my example, I'm storing date as String instead of Date object which is not the recommended way
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelBasic {
public static void main(String[] args) throws IOException {
String excelFileName = "/Users/home/Test3.xls";
FileOutputStream fos = new FileOutputStream(excelFileName);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle style = wb.createCellStyle();
XSSFSheet sheet = wb.createSheet("sheet");
XSSFFont urlFont = wb.createFont();
style.setFont(urlFont);
String monthEndDate = "31-Dec-17";
DataFormat df = wb.createDataFormat(); //these 3 lines are enough
short dateFormat = df.getFormat("dd-MMM-yy"); // 2nd
style.setDataFormat(dateFormat); // 3rd
for (int r = 0; r < 1; r++) {
XSSFRow row = sheet.createRow(r);
row.setHeight((short) -1);
for (int c = 0; c < 3; c++) {
XSSFCell cell = row.createCell(c);
String ss = "31-Dec-17";
cell.setCellValue(ss);
style.setWrapText(true);
cell.setCellStyle(style);
}
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
wb.write(baos);
byte[] myByteArray = baos.toByteArray();
fos.write(myByteArray);
fos.flush();
}
finally {
wb.close();
fos.close();
}
}
}
I wanted to set font of the title row in a spreadsheet bold. I was able to do that in my main function with the following code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet dataSheet = workbook.createSheet("Data");
HSSFCellStyle fontStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
fontStyle.setFont(font);
Row row = dataSheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(fontStyle);
cell.setCellValue("ID");
Since createCellStyle is method of HSSFWorkbook, if I write to the sheet by calling a function which takes the sheet but not the workbook as parameter, how do I set the cell style?
public class SummaryXlsCreator {
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet dataSheet = workbook.createSheet("Data");
writeCDMarker(dataSheet);
}
public static void writeCDMarker(HSSFSheet sheet) {
int rownum = 0;
int cellnum = 0;
Row row = sheet.createRow(rownum++);
Cell cell = row.createCell(cellnum++);
// write first row of sheet "Data"
cell.setCellValue("ID");
}
Use getWorkbook() to get the parent and proceed with the existing code.
sheet.getWorkbbok().createCellStyle();
https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html
You can use the static CellUtil.setCellStyleProperties(Cell cell, Map<String, Object> properties) to format your cell without needing a reference to your workbook or sheet.
Example usage:
// Format cell into date time format with "m/d/yy h:mm",
// which is converted to user's locale in Excel.
CellUtil.setCellStyleProperties(cell, Collections.singletonMap(CellUtil.DATA_FORMAT, (short) 22));