How to insert line break into excel using java? - java

I am read from a database column which stores data like
testing\n
testing\n
I am then using the jxl.write.WritableWorkbook methods to generate the excel file that will read from this column.
However when being displyed as excel There are no line break in the column data.
What is the reason and how should i resolve this?

You might try: WritableCellFormat.setWrap(true)
Look here: http://jexcelapi.sourceforge.net/resources/faq/

I searched the internet since i needed an answer and here it is...
From JExcel API FAQ:
How do I add a newline or carriage-return to a Label cell?
Use "\012" or "\n". Also make sure to turn on cell wrapping with WritableCellFormat.setWrap(true) or the newline will show up as a square (unknown character).
I tested it and it worked for "\012" or "\n" as i put also .setWrap(true) and i tested it with
WritableCellFormat times16format =
new WritableCellFormat(times16font);
times16format.setWrap(true);
times16format.setAlignment(Alignment.RIGHT);
times16format.setBorder(Border.ALL, BorderLineStyle.HAIR);
//Merge col[0-2] and row[0]
sheet.mergeCells(0, 0, 2, 0);
Label leftPartLabel =
new Label(
0,
0,
reportKingdomData + "\012" + dateData + " " + MyDateFormat.format(new Date()) + timeData + "\n" + MyTimeFormat.format(new Date()),
times16format);
sheet.addCell(leftPartLabel);
Insert Line In jxl JExcel API

Try this:
for (int row = 0; row<100; row++)
{
sheet.addCell(new Label(0,row,"Testing "+row);
}
Feel comfortable to let me know, if you are facing problem and don't forget to mark/upvote correct answer.

Related

Apache POI PPT (Java) - Updating TextShape keeping text formatting/shape formatting

I am trying to produce several reports (i.e. N PPTX files) based on different inputs/for different users on the same PPTX template I created.
I have several preformatted XSLFTextShape on the PPTX template that contains a single XSLFTextParagraph already formatted (i.e. both the shape and the text). Each shape contains a particular placeholder that I need to substitute with a dynimic value. I have this value in a Map (placeholder,newValue). I am successful in updating the placeholder with the new value using:
textShape.clearText();
XSLFTextRun run = paragraph.addNewTextRun();
run.setText(newText);
So, when I produce the PPTX in output the text is updated but font color, font formatting, font size are changed compared to those I defined in the template. How can I keep the same formatting?
Any solutions to simply change the text while keeping original formatting?
Thanks in advance!
For everybody which may be interested in this topic in the future - I post the solution (working if one TextBox has a single Paragraph). This solution loops on all text boxes and in the case one contain one of the vales specified in the Placeholder->newValue map, it will update it maintaining the formatting.
public static void updateTextBoxesWithDesiredValues(XMLSlideShow ppt, Map<String, String> placeHolderDefinedValue) {
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + " ########## Updating single text box content...");
List<XSLFSlide> allSlides = ppt.getSlides();
int updatedElements = 0;
for (XSLFSlide currentSlide : allSlides) {
for (XSLFShape shape : currentSlide.getShapes()) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape textBox = (XSLFTextShape) shape;
String elementTextContent = textBox.getText();
for (Object key : placeHolderDefinedValue.keySet()) {
if (elementTextContent.equals(key)) {
List<XSLFTextParagraph> textBoxParagraphs = textBox.getTextParagraphs();
List<XSLFTextRun> textBoxParagraphTextRuns = textBoxParagraphs.get(0).getTextRuns();
//System.out.println("########################## check paragraph number in textbox: " + textBoxParagraphs.size() + " - TextRuns: " + textBoxParagraphs.get(0).getTextRuns().size());
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + updatedElements + ") Updating: " + textBox.getText() + " --> " + placeHolderDefinedValue.get(key));
for (XSLFTextRun r : textBoxParagraphTextRuns) {
r.setText(placeHolderDefinedValue.get(key));
}
updatedElements++;
//break;
}
}
}
}
}
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + " Total Text Element Content Updated: " + updatedElements + " #########################");
}
It's kind of horrible - but yeah there's a reason they called it "POI".
Here's my approach to "only reset text" of an existing XSLFTextShape (that must have at least some text pre-set!):
textShape.getTextParagraphs().get(0).getTextRuns().get(0).setText(text);
for (int i = 1; i < textShape.getTextParagraphs().get(0).getTextRuns().size(); i++) {
textShape.getTextParagraphs().get(0).getTextRuns().get(i).setText("");
}
for (int i = 1; i < textShape.getTextParagraphs().size(); i++) {
textShape.getTextParagraphs().get(i).getTextRuns().stream().filter(tr -> !tr.getRawText().equals("\n")).forEach(tr -> tr.setText(""));
}
It will replace all existing text(paragraphs/runs) with "empty" text, but linebreaks can't be replaced for some reason. So this might leave you with some trailing lines - as they usually(!) are transparent this won't really hurt a lot.
.clearText / removing paragraphs either destoyed the formatting for me, or didn't work. Trying to reset the style (fontColor, fontFamily, fontSize, isBold, isItalit, ...) didn't result in satisfying results :(

how make a new line character from XML to be detected if passing from ArrayList into excel?

I need some help to pass multi line text that I stored in ArrayLists into Excel cells. I made a parser to get values from each tag and now i'm trying to build my excel but I faced a problem that text from tags like this
<ProgramName>Mirror \n 2017</ProgramName>
looks like this Mirror \\n 2017if I manually copy it into setCellValue and I thinks this double slash is my problem but I have no idea why it's even here. and my code can't make it into a new line
//progName style
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cs.setVerticalAlignment(VerticalAlignment.CENTER);
cs.setAlignment(HorizontalAlignment.CENTER);
//progName text
Row row = sheet1.createRow((short) 1);
Cell cell = row.createCell((short) 1);
row.setHeightInPoints((2*sheet1.getDefaultRowHeightInPoints()));
String asd = String.valueOf(ProgramName.get(0));
cell.setCellValue(asd);
sheet1.addMergedRegion(new CellRangeAddress(1,1,1,8));
thanks to Andreas
String asd = String.valueOf(ProgramName.get(0)).replaceAll("\\\\n", "\n");

How to set a cell format to Text

I am using Apache-POI 3.14. I have a need to lock-down a cell to a "Text" format. The data in my cell might be all digits, but it is still considered a string. When I write the cell, I do it like this:
cell.setCellValue("001");
cell.setCellType(Cell.CELL_TYPE_STRING);
When I open the output workbook in Excel, the cell contains the correct value ("001") and it displays with a small green triangle in the corner. Hovering over the exclamation point displays the hover text The number in this cell is formatted as text or preceded by an apostrophe. When I look at the cell formatting (Right-click -> Format cells), the "Category" is displayed as "General". I expected this to be "Text".
The problem arises when a user modifies the value in the cell by entering only digits. Because the "Category" is "General", the value is entered and displayed as a number, removing leading zeroes and right-justified.
How can I achieve the same result as Excel's "Format cells" dialog?
You can try to set the cell-format to text via
DataFormat fmt = wb.createDataFormat();
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
fmt.getFormat("#"));
cell.setCellStyle(cellStyle);
Note: CellStyles shoudl be re-used for all applicable cells, do not create new ones for every cell.
You could also try to use the "Ignore errors" feature in the .xlsx format, however support for it is not fully done yet, see Issue 46136 and Issue 58641 for some ongoing discussion.
See also this MSDN page for some additional information
For HSSF,
DataFormat fmt = workbook.createDataFormat();
CellStyle textStyle = workbook.createCellStyle();
textStyle.setDataFormat(fmt.getFormat("#"));
sheet.setDefaultColumnStyle(0, textStyle);
It just sets the whole column style as Text and set category as Text .
However, if you are using XSSF format, it doesn't work(I am using Apache Poi 3.15 and didn't work for me).
In this case you have set style to each cell you want to treat as text in addition to above code using:
cell.setCellStyle(textStyle);
Regarding error, you could use
sheet.addIgnoredErrors(new CellRangeAddress(0,9999,0,9999),IgnoredErrorType.NUMBER_STORED_AS_TEXT );
It ignores the NUMBER_STORED_AS_TEXT error for row 0 till 9999 and column 0 till 9999 and you wont see it.
Look like OP was asking for Apache solution. After some searching I found this answer:
HSSFCellStyle style = book.createCellStyle();
style.setDataFormat(BuiltInFormats.getBuiltInFormat("text"));
In this case, I'm using Apache-POI 3.15, and I had the same problem, so I validated the data in my style, I need numbers >0 and strings:
try {
if (Integer.parseInt(field + "") >= 0) {
int valor = Integer.parseInt(field + "");
cell.setCellValue(valor); //Int
}
} catch (NumberFormatException nfe) {
// no int
try {
if (Double.parseDouble(field + "") >= 0) {
double valor = Double.parseDouble(field + ""); //double
cell.setCellValue(valor);
}
} catch (NumberFormatException nfe2) {
cell.setCellValue(field + ""); //String
}
}
For Apache POI 4.0.1 :
XSSFSheet sheet = workbook.createSheet("MySheetName");
sheet.addIgnoredErrors(new CellRangeAddress(0, 9999, 0, 9999), IgnoredErrorType.NUMBER_STORED_AS_TEXT);
Be careful to cast your sheet to org.apache.poi.xssf.usermodel.XSSFSheet and not to org.apache.poi.ss.usermodel.Sheet, otherwise the method addIgnoredErrors wil be unknown.

How to add table heading drop-down with Apache Poi

I'm generating Excel tables with Apache POI, but my generated tables lack the drop-down menu on each header that appear when I "format as table" in Excel itself.
I'd like to generate this:
But instead I get this:
I'm following this blog post, and my code looks like this:
XSSFTable table = sheet.createTable();
table.setDisplayName("Data");
CTTable ctTable = table.getCTTable();
ctTable.setDisplayName("Data");
ctTable.setId(1L);
ctTable.setName("DATA");
CTTableStyleInfo table_style = ctTable.addNewTableStyleInfo();
table_style.setName("TableStyleMedium9");
table_style.setShowColumnStripes(false);
table_style.setShowRowStripes(true);
Each column is then created like this:
CTTableColumn column = ctColumns.addNewTableColumn();
column.setName(headers.get(i));
column.setId(i + 1);
What am I missing?
Thanks to Alan Hay for the clue - the solution is to add an auto-filter, but this needs to be added as a CTAutoFilter for each individual column of the CTTable. The working solution looks like this:
CTTableColumns ctColumns = ctTable.addNewTableColumns();
CTAutoFilter autofilter = ctTable.addNewAutoFilter();
ctColumns.setCount(table_headers.size());
for(int i = 0; i < table_headers.size(); i++) {
CTTableColumn column = ctColumns.addNewTableColumn();
column.setName(table_headers.get(i));
column.setId(i + 1);
CTFilterColumn filter = autofilter.addNewFilterColumn();
filter.setColId(i + 1);
filter.setShowButton(true);
}
When auto-sizing columns, it's also necessary to add extra width for the drop down menu:
for(int i = 0; i < table_headers.size(); i++) {
sheet.autoSizeColumn(i);
// Include width of drop down button
sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 1000);
}
It is not exactly clear from the example you quoted whether applying the Table styling should create the filter dropdowns for you or not.
However you can explicitly call setAutoFilter() as below to have the filter dropdowns set.
e.g.
CellReference start = table.getStartCellReference();
CellReference end= table.getEndCellReference();
sheet.setAutoFilter(new CellRangeAddress(...);

Querying/Accessing/Retrieving Header row in Google Spreadsheet

I'm accessing a public Google Docs Spreadsheet using the Google Sheets API. The API says that when you query a list-feed for a worksheet, you get back a list of rows excluding the first row, which is the header row (by convention).
Is there a way to access the header row? I see that you can use the cells feed to request specific cells:
// Fetch column 4, and every row after row 1.
URL cellFeedUrl = new URI(worksheet.getCellFeedUrl().toString()
+ "?min-row=2&min-col=4&max-col=4").toURL();
CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
Is there another way that is more explicit, to retrieve the header row?
I searched long and hard, but it appears there is no semantically explicit way to grab headers out of a spreadsheet. As I mentioned in the question, you can use the cell feed so this is what I did:
URL cellFeedUrl = new URL(worksheet.getCellFeedUrl().toString() + "?min-row=1&max-row=1");
CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
for(CellEntry cellEntry : cellFeed.getEntries()) {
System.out.print(cellEntry.getCell().getValue() + ",");
}
System.out.println();
The important part is the ?min-row=1&max-row=1 part. This gives you all the cells in the first row of the sheet. By convention, the very first row in a worksheet is treated as the header.
getTags()
this might return an iterable with "name", "address", "manager", "employeeid"."
https://developers.google.com/gdata/javadoc/com/google/gdata/data/spreadsheet/CustomElementCollection#getTags()
Example - ListDemo.java
public void printAndCacheEntry(ListEntry entry) {
// We only care about the entry id, chop off the leftmost part.
// I.E., this turns http://spreadsheets.google.com/..../cpzh6 into cpzh6.
String id = entry.getId().substring(entry.getId().lastIndexOf('/') + 1);
// Cache all displayed entries so that they can be updated later.
entriesCached.put(id, entry);
out.println("-- id: " + id + " title: " + entry.getTitle().getPlainText());
for (String tag : entry.getCustomElements().getTags()) {
out.println(" <gsx:" + tag + ">"
+ entry.getCustomElements().getValue(tag) + "</gsx:" + tag + ">");
}
}
http://gdata-java-client.googlecode.com/svn-history/r497/trunk/java/sample/spreadsheet/list/ListDemo.java
I have never used this, so not 100% sure. But looks like what you want.

Categories