Apache POI Word Styles How do I get rid of gaps? - java

Apache POI Word
table, text, enter, etc. How do I get rid of gaps in everything?
Can I do it like no spacing in word style?
Apache POI Word
table, text, enter, etc. How do I get rid of gaps in everything?
I want to do it like TO
public class PoiTest {
public static void main(String[] args) throws IOException {
XWPFDocument doc = new XWPFDocument();
XWPFTable table = doc.createTable();
XWPFTableRow row1 = table.getRow(0);
row1.getCell(0).setText("First Row, First Column");
row1.addNewTableCell().setText("First Row, Second Column");
row1 = table.createRow();
row1.getCell(0).setText("Second Row, First Column");
row1.getCell(1).setText("Second Row, Second Column");
row1 = table.createRow();
row1.getCell(0).setText("Third Row, First Column");
row1.getCell(1).setText("Third Row, Second Column");
XWPFParagraph title = doc.createParagraph();
XWPFRun titleRun = title.createRun();
titleRun.setText("First");
title = doc.createParagraph();
titleRun = title.createRun();
titleRun.setText("Second");
FileOutputStream out;
try {
out = new FileOutputStream("c:\\test\\test.docx");
doc.write(out);
System.out.println("ok!!!");
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

Bad news (or... possibly good news). When running your code as-is, it looks just fine:
Inside the running code, the result of System.getProperty("java.version") is 11.0.16 (although Eclipse claims I am using OpenJDK 17.0.4)
Resulting .docx file was opened with LibreOffice 7.0.4.2 to get the above screenshot.

Related

how create TextBox in a cell of table in document .docx using apache poi

I used Javafx and
I created a table using apache poi:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFTable table = document.createTable(4, 3);
and created the paragraph like the paragraph below:
XWPFParagraph p1 = table.getRow(0).getCell(2).getParagraphs().get(0);
XWPFRun r1 = p1.createRun();
r1.setText(category_number.getText() + category.toString());
Now, I want create a TextBox in a one cell of a row but don't know how address Cell and Row to a textBox and set text and alignment textBox.
Please Help me ):
A text box in a *.docx is a shape in the document content. Creating shapes is not yet implemented in XWPF. But it can be done using the underlying ooxml-schemas classes.
Example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTxbxContent;
import com.microsoft.schemas.vml.CTGroup;
import com.microsoft.schemas.vml.CTShape;
import org.w3c.dom.Node;
public class CreateWordTextBoxInTable {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
XWPFTable table = document.createTable(4, 3);
// table header row
for (int c = 0; c < 3; c++ ) {
paragraph = table.getRow(0).getCell(c).getParagraphArray(0);
if (paragraph == null) paragraph = table.getRow(0).getCell(c).addParagraph();
run = paragraph.createRun();
run.setText("Column " + (c+1));
}
// get run in cell for text box
XWPFTableCell cell = table.getRow(1).getCell(1);
paragraph = cell.getParagraphArray(0);
if (paragraph == null) paragraph = cell.addParagraph();
run = paragraph.createRun();
// create inline text box in run
// first crfeate group shape
CTGroup ctGroup = CTGroup.Factory.newInstance();
// now add shape to group shape
CTShape ctShape = ctGroup.addNewShape();
ctShape.setStyle("width:100pt;height:36pt");
// add text box content to shape
CTTxbxContent ctTxbxContent = ctShape.addNewTextbox().addNewTxbxContent();
XWPFParagraph textboxparagraph = new XWPFParagraph(ctTxbxContent.addNewP(), (IBody)cell);
textboxparagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun textboxrun = textboxparagraph.createRun();
textboxrun.setText("The TextBox content...");
textboxrun.setFontSize(10);
// add group shape as picture to the run
Node ctGroupNode = ctGroup.getDomNode();
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
FileOutputStream out = new FileOutputStream("test.docx");
document.write(out);
out.close();
}
}
This code was tested using apache poi 4.0.1 and needs the ooxml-schemas-1.4.jar in class path.

JExcel - Modify Multiple Cells Before Closing WritableWorkbook

I am trying to put a title in cell (0,0) and then use a for() loop to add file paths into each following row. However, I am only able to add one line of code; after the title, no other cells in the Excel document are modified.
Here's where I create the file:
private void chooseSheetActionPerformed(java.awt.event.ActionEvent evt) {
sheetNum = chooseSheet.getSelectedIndex() - 1;
try {
WritableWorkbook workbook = Workbook.createWorkbook(newXls);
workbook.createSheet("Sheet1", 0);
workbook.write();
workbook.close();
writeXls();
} catch (Exception ex) {
Logger.getLogger(NewScore.class.getName()).log(Level.SEVERE, null, ex);
}
}
And here's where I try to write to it:
public void writeXls() throws Exception {
Workbook wb = Workbook.getWorkbook(newXls);
WritableWorkbook copy = Workbook.createWorkbook(newXls, wb);
WritableSheet ws = copy.getSheet(sheetNum);
WritableCell cell;
// Body Part - Title
Label lab = new Label(0,0,partName);
cell = (WritableCell) lab;
ws.addCell(cell);
copy.write();
// Image Info
int i = 1;
for (File file : imageArray(dir)) {
Label label = new Label (0,i,"test" + i);
cell = label;
ws.addCell(cell);
copy.write();
i++;
}
copy.close();
}
Is there a way to make my for() loop work, or do I need to go about this a different way?
Thanks!
Okay. Initially I was confused wether you are trying to create a new workbook or edit an existing one. But it looks like you need a new one here.
It appears there were two issues in the code example.
First one is that you retrieved just created excel file and copied its content into itself.
Workbook wb = Workbook.getWorkbook(newXls);
WritableWorkbook copy = Workbook.createWorkbook(newXls, wb);
Another thing that I noticed is that in order to save all the changes it is required to call write on the WritableWorkbook instance only once in the end.
I finished with such code.
private static final String FILE_NAME = "D:/test_out.xls";
private static final String SHEET_NAME = "Test sheet name";
private static final int SHEET_INDEX = 0;
private static final String HEADER = "My header";
public static void main(String[] args) throws Exception {
WritableWorkbook writableWorkbook = Workbook.createWorkbook(new File(FILE_NAME));
WritableSheet writableSheet = writableWorkbook.createSheet(SHEET_NAME, SHEET_INDEX);
int columnIndex = 0;
int rowIndex = 0;
writableSheet.addCell(new Label(columnIndex, rowIndex, HEADER));
for (String value : Arrays.asList("First value", "Second value", "Another value")) {
writableSheet.addCell(new Label (columnIndex, ++rowIndex, value));
}
writableWorkbook.write();
writableWorkbook.close();
}
It created for me an excel file with one sheet. The sheet contains one column with 4 cells: My header, First value, Second value, Another value. Of course, you are free to put there any values you need :)

Apache POI writes only one record

I am writing some data into excel file using Apache POI but for some reason the file shows only the last record (1 record only). I have list of POLJO that I am passing. I am also iterating through the cells but all I get is just one record.
Method to write in excel
public void writeToExcel(List<NYProgramTO> to){
try {
Workbook workBook = new HSSFWorkbook();
CreationHelper helper = workBook.getCreationHelper();
Sheet sheet = workBook.createSheet("NY_PPA_P3_Sheet");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("First Name");
headerRow.createCell(1).setCellValue("Last Name");
headerRow.createCell(2).setCellValue("Policy Number");
headerRow.createCell(3).setCellValue("Zip Code");
headerRow.createCell(4).setCellValue("Date of Birth");
if(to != null){
int size = to.size();
for(int i = 0; i < size; i++){
NYProgramTO nyP= to.get(i);
Row row = sheet.createRow(1);
row.createCell(0).setCellValue(nyP.getFirstName());
row.createCell(1).setCellValue(nyP.getLastName());
row.createCell(2).setCellValue(nyP.getPolicyNumber());
row.createCell(3).setCellValue(nyP.getZipCode());
row.createCell(4).setCellValue(nyP.getDateOfBirth());
}
}
FileOutputStream stream = new FileOutputStream("NY_PPA_P3.xlsx");
workBook.write(stream);
stream.close();
System.out.println("NY_PPA_P3.xlsx created successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
If by "only one record" you mean that only one row is appearing, this is probably easily fixable by making sure that you increment the Row that is being created before writing the Cells.
Try changing:
Row row = sheet.createRow(1);
to:
Row row = sheet.createRow(i+1);

Unable to read entire cell of a .doc file using Apache POI

In one of my projects I need to read images from a .doc file using Apache POI. For each row there is a cell containing an images(one, two, three, etc. ) which I need to read out along side with text data.
So I tried the following code
FileInputStream fileInputStream = new FileInputStream(file);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fileInputStream);
HWPFDocument doc = new HWPFDocument(poifsFileSystem);
Range range = doc.getRange();
PicturesTable pictureTable = doc.getPicturesTable();
PicturesSource pictures = new PicturesSource(doc);
Paragraph tableParagraph = range.getParagraph(0);
Table table = range.getTable(tableParagraph);
TableRow row = table.getRow(0);
TableCell cell1 = row.getCell(0);
for (int j = 0; j < cell1.getParagraph(0).numCharacterRuns(); j++) {
CharacterRun cr = cell1.getParagraph(0).getCharacterRun(j);
if (pictureTable.hasPicture(cr)) {
logger.debug("Has picture If--");
Picture picture = pictures.getFor(cr);
logger.debug("pictures Description--" + picture.getDescription());
}
}
Now I am able to read images of a particular cell, but the problem is I am not able to read all the images of a cell means, I am able to read image before the text and image in between the text, but I am not able to read the image which is followed by the text. Example "image_1---some text---image_2 some text---.image_3". Now in this case I am not able to read image_3 only. What should I do, So I can read image_3 also. I searched a lot but no luck till now. Hope someone knows the way to do this. Thanks in Advance.
With the HWPFDocument, I am having problems, too. If you have a chance to change the Word documents to docx before processing, here's an example that works with XWPFDocuments:
FileInputStream fileInputStream = new FileInputStream(file);
XWPFDocument doc = new XWPFDocument(fileInputStream);
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph para : cell.getParagraphs()) {
for (XWPFRun run : para.getRuns()) {
for (XWPFPicture pic : run.getEmbeddedPictures()) {
System.out.println(pic.getPictureData());
}
}
}
}
}
}

Edit Microsoft-office .doc file in java using Apache POI

I'm writing java code to achieve the followings.
1.Read given Microsoft-office document(.doc) file.
2.Search for given string in the file.
3.Delete the given String located in any place.
4.Insert or replace any given string at specified position.
5.Write and save the updated file content into new .doc file.
I have written a code to read, search, insert or replace, delete and save the file and it's working good, but i couldn't able to preserve the text format(such as font color, font size, justification, left and right indent, styles etc) applied in the input file.
please anyone helps me to solve the issue.
Thank you
I'll added new solution for styling Ms-Word Document..
public class CreateDocumentFromScratch {
public static void main(String[] args) {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
paragraphOne.setAlignment(ParagraphAlignment.CENTER);
paragraphOne.setBorderBottom(Borders.SINGLE);
paragraphOne.setBorderTop(Borders.SINGLE);
paragraphOne.setBorderRight(Borders.SINGLE);
paragraphOne.setBorderLeft(Borders.SINGLE);
paragraphOne.setBorderBetween(Borders.SINGLE);
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setBold(true);
paragraphOneRunOne.setItalic(true);
paragraphOneRunOne.setText("Hello world! This is paragraph one!");
paragraphOneRunOne.addBreak();
XWPFRun paragraphOneRunTwo = paragraphOne.createRun();
paragraphOneRunTwo.setText("Run two!");
paragraphOneRunTwo.setTextPosition(100);
XWPFRun paragraphOneRunThree = paragraphOne.createRun();
paragraphOneRunThree.setStrike(true);
paragraphOneRunThree.setFontSize(20);
paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
paragraphOneRunThree.setText(" More text in paragraph one...");
XWPFParagraph paragraphTwo = document.createParagraph();
paragraphTwo.setAlignment(ParagraphAlignment.DISTRIBUTE);
paragraphTwo.setIndentationRight(200);
XWPFRun paragraphTwoRunOne = paragraphTwo.createRun();
paragraphTwoRunOne.setText("And this is paragraph two.");
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
document.write(outStream);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use the following code:
public class EditingWord{
public static void main(String[] args) {
// TODO Auto-generated method stub
String filename = "path to input file/file_input_name";
List<String> paraList = new ArrayList<String>();
try {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
List<XWPFParagraph> paragraphList = doc.getParagraphs();
for (XWPFParagraph para : paragraphList) {
if ((para.getStyle() != null) && (para.getNumFmt() != null)) {
for (XWPFRun run : para.getRuns()) {
String text = run.text();
text = text.replaceAll(text, "replacement" + text);
run.setText(text, 0);
}
}
}
doc.write(new FileOutputStream("path to your file/output_File_name"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
In case if you want to save your content to same file, you can change doc.write(new FileOutputStream("path to your inpufile/input_File_name"));
I'll suggest you to use of Apache POI Documentation.
I'll do some experiment using documentation and getting text formatting easily for Ms-Excel Sheet..
http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCellStyle.html
http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html
I was browsing through the API when I saw the DataFormat class and its hierarchy,
the BuiltinFormats class,
and the setDataFormat method of the CellStyle class.
So did some experimentation, and the code below seems to work!
XSSFCellStyle textFormatStyle = book.createCellStyle();
textFormatStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("text"));
XSSFCell cell = row.createCell(columnIndex++);
cell.setCellStyle(textFormatStyle);
Now, once spreadsheet is created,
you can edit a cell, and when you tab out,
the format remains "text".
I having showing you another way with full example..
In which I'll show one effect further you can add as per your requirement...
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Style example");
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("This is bold");
cell.setCellStyle(style);
font = workbook.createFont();
font.setItalic(true);
style = workbook.createCellStyle();
style.setFont(font);
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("This is italic");
cell.setCellStyle(style);
try {
FileOutputStream out = new FileOutputStream(new File("C:\\style.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This code will generate bellow output :

Categories