I am unable to write data into second sheet of excel using Apache POI in selenium web driver. It showing up a Null point exception error. However, i am able to write data in first sheet. Below is my code,
package RWExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcel {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File src = new File("D:/selenium/Test/ReadExcel.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wbook = new XSSFWorkbook(fis);
XSSFSheet sheet0 = wbook.getSheetAt(1);
sheet0.getRow(0).createCell(2).setCellValue("Pass");
sheet0.getRow(1).createCell(2).setCellValue("Fail");
FileOutputStream output = new FileOutputStream(src);
wbook.write(output);
wbook.close();
}
}
Related
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("D://New Microsoft Excel Worksheet.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.createSheet("newsheet5");
CTWorksheet ctSheet = sheet.getCTWorksheet();
CTCustomProperties props = ctSheet.addNewCustomProperties();
props.addNewCustomPr().setId("APACHE POI");
props.addNewCustomPr().setName("Tender no = 48");
props.addNewCustomPr().setId("APACHE POI 2");
props.addNewCustomPr().setName("tender no = 58");
ctSheet.setCustomProperties(props);
FileOutputStream out = new FileOutputStream("D://New Microsoft Excel Worksheet.xlsx");
wb.write(out);
out.close();
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Xlsx file is corrupted after writing custom properties at sheet level.
I'm getting an error message as 'excel cannot open the file because the file format or file extension is not valid . Vefiry that the file has not been corrupted and the file extension matches the format of the file' when tried open the excel file.
Sheet custom properties only are useable using VBA. They are stored in the Excel file but the values are within binary document parts customProperty1.bin, customProperty2.bin, ... This is nothing what apache poi provides access to until now.
Using XSSF one needs creating the binary document part, then getting the relation Id to that binary document part. Then set CTCustomProperties - CTCustomProperty. There the Id points to the binary document part containing the value and the name is the property name.
Following complete example shows this. It is tested and works using current apache poi 4.1.2. It needs ooxml-schemas-1.4.jar being in class path because default poi-ooxml-schemas-4.1.2.jar does not contain all needed low level CT*-classes.
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import java.nio.charset.StandardCharsets;
class CreateExcelSheetCustomProperties {
static void setSheetCustomProperty(XSSFSheet sheet, String customPropertyName, String customPropertyValue) throws Exception {
OPCPackage opcpackage = sheet.getWorkbook().getPackage();
int i = opcpackage.getUnusedPartIndex("/customProperty#.bin");
PackagePartName partname = PackagingURIHelper.createPartName("/customProperty" + i + ".bin");
PackagePart part = opcpackage.createPart(partname, "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty");
POIXMLDocumentPart customProperty = new POIXMLDocumentPart(part) {
#Override
protected void commit() throws IOException {
PackagePart part = getPackagePart();
OutputStream out = part.getOutputStream();
try {
out.write(customPropertyValue.getBytes(StandardCharsets.UTF_16LE));
out.close();
} catch (Exception ex) {
ex.printStackTrace();
};
}
};
String rId = sheet.addRelation(null, XSSFRelation.CUSTOM_PROPERTIES, customProperty).getRelationship().getId();
CTWorksheet ctSheet = sheet.getCTWorksheet();
CTCustomProperties props = ctSheet.getCustomProperties();
if (props == null) props = ctSheet.addNewCustomProperties();
CTCustomProperty prop = props.addNewCustomPr();
prop.setId(rId);
prop.setName(customPropertyName);
}
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {
XSSFSheet sheet = workbook.createSheet();
setSheetCustomProperty(sheet, "APACHE POI", "Tender no = 48");
setSheetCustomProperty(sheet, "APACHE POI 2", "tender no = 58");
workbook.write(fileout);
}
}
}
I've been struggling with the same issue and found a way to make it work, but it's far from optimal. Here it is anyway and hopefully you or someone else can come up with a better method.
package temp.temp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCustomProperties;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCustomProperty;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
public class Temp2 {
public static void main(String[] args) {
File inputFile = new File("C:\\myspreadsheet.xlsx");
try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inputFile))) {
XSSFWorkbook wb = new XSSFWorkbook(fis);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
System.out.println("\nSheetName=" + sheet.getSheetName());
CTWorksheet ctSheet = sheet.getCTWorksheet();
CTCustomProperties props = ctSheet.getCustomProperties();
if (props != null) {
List<CTCustomProperty> propList = props.getCustomPrList();
propList.stream().forEach((prop) -> {
POIXMLDocumentPart rel = sheet.getRelationById(prop.getId());
if (rel != null) {
try (InputStream inp = rel.getPackagePart().getInputStream()) {
byte[] inBytes = inp.readAllBytes();
// By experimentation, byte array has two bytes per character with least
// significant in first byte which is UTF-16LE encoding. Don't know why!
String value = new String(inBytes, "UTF-16LE");
System.out.println(" " + prop.getName() + "=" + value);
} catch (IOException ioe) {
//Error
}
}
});
}
}
wb.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("End");
}
}
Note that CTWorksheet comes from poi-ooxml-schemas-xx.jar and CustomProperties from ooxml-schemas-yy.jar, so both have to be on the classpath. If you're using modules (as I am), this gives big problems! Good Luck
how can we unprotect the word document using java apache poi? I have protected the document as read-only using password pro-grammatically.Now I want to unprotect it. How can we do ? Is there any method to unprotect the document. I have used removePasswordProtection() but that document is not editable even after using that method.
The sample code that I have used for protection is
XWPFDocument document=new XWPFDocument();
document.enforceReadonlyProtection(strPassword,HashAlgorithm.sha1);
The document is getting protected successfully.
But when I am unprotecting document using the below code snippet it is not working.
if(document.isEnforcedReadonlyProtection())
{
if(document.validateProtectionPassword(strPassword))
{
document.removeProtectionEnforcement();
}
}
Can anyone help me what method that I can use to unprotect the document?
Cannot reproducing.
Following code produces two Word documents. One, WordProtected.docx, which is protected and one, WordUnprotected.docx in which protection is removed.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.poifs.crypt.HashAlgorithm;
class XWPFReadOnlyProtection {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
String strPassword = "password";
document.enforceReadonlyProtection(strPassword, HashAlgorithm.sha1);
FileOutputStream fileout = new FileOutputStream("WordProtected.docx");
document.write(fileout);
fileout.close();
document.close();
document = new XWPFDocument(new FileInputStream("WordProtected.docx"));
document.removeProtectionEnforcement();
fileout = new FileOutputStream("WordUnprotected.docx");
document.write(fileout);
fileout.close();
document.close();
}
}
use this code for Word to Protect
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class WordTest {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("D:\\govind.doc");
BufferedInputStream bin = new BufferedInputStream(in);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bin);
Biff8EncryptionKey.setCurrentUserPassword("P#ssw0rd");
HWPFDocument doc = new HWPFDocument(poiFileSystem);
Range range = doc.getRange();
FileOutputStream out = new FileOutputStream("D:\\govind.doc");
doc.write(out);
out.close();
}
}
this is use for protected word File unportected
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class wordFileTest {
public static void main(String[] args) throws IOException {
geenrateUnprotectedFile("D:\\","govind","1234");
}
public static void geenrateUnprotectedFile(String filePath,String fileName,String pwdtxt) {
try {
FileInputStream in = new FileInputStream(filePath+fileName+".doc");
BufferedInputStream bin = new BufferedInputStream(in);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bin);
Biff8EncryptionKey.setCurrentUserPassword(pwdtxt);
HWPFDocument doc = new HWPFDocument(poiFileSystem);
String docType=doc.getDocumentText();
FileOutputStream out = new FileOutputStream(filePath+fileName+"12.doc");
out.write(docType.getBytes());
System.out.println("don");
}catch (Exception e) {
e.printStackTrace();
}
}
}
Wanted to know how to read the same Excel file in java using multi-thread. I tried reading the Excel file using XSSFWorkbook, but when the initialization step is executed the program is termination without even entering to catch or finally block using testNG framework
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class MultiThread implements Runnable {
#BeforeSuite
#Parameters({"masterFileName"})
public void threadExm (String masterFileName) {
Thread guruThread1 = new Thread("Test1");
Thread guruThread2 = new Thread("Test2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
#Override
public void run() {
try {
String excelFilePath = System.getProperty("user.dir") + "/inputfiles/Master.xlsx";
FileInputStream inputStream;
inputStream = new FileInputStream(new File(excelFilePath));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
test(wb);
} catch (Exception e) {
e.printStackTrace();
}
}
public void test(XSSFWorkbook wb){
System.out.println(wb.getSheet("Sheet1").getLastRowNum());
}
}
when the first column of the row is empty, excel write is not working. second and remaining column values also checking if the first column is filled or empty. any reason behind or how to over come this issue.
Test1: first column empty
package DataDrivern;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWrite {
public static void main(String[] args) throws Exception
{
File src=new File("D:\\Selenium Learning\\input.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet ws=wb.getSheet("Sheet2");
System.out.println("excel read successfully");
ws.getRow(0).createCell(0).setCellValue("test");
FileOutputStream fos=new FileOutputStream(src);
wb.write(fos);
wb.close();
}
}
Output
excel read successfully
Exception in thread "main" java.lang.NullPointerException
at DataDrivern.ExcelWrite.main(ExcelWrite.java:22)
Test 2: first column not empty
before running code:
package DataDrivern;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWrite {
public static void main(String[] args) throws Exception
{
File src=new File("D:\\Selenium Learning\\input.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet ws=wb.getSheet("Sheet2");
System.out.println("excel read successfully");
ws.getRow(0).createCell(0).setCellValue("test");
FileOutputStream fos=new FileOutputStream(src);
wb.write(fos);
wb.close();
}
}
after running code
Wrong usage of method instead of getRow you have to use createRow
ws.createRow(0).createCell(0).setCellValue("test");
This will write string "test" to row 0 and column 0
I wrote a code in Java to read an excel(.xlsx) file and save the same file with different name. The code is working fine but the size of original and generated excel is different. I got the problem as on saving the original, the excel is losing some data. But when I opened the generated file through Ms Excel it get restored to its original size. What could I use in my code so that no data is lost?
Code is:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class MyExcel {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("D:\\test.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(1);
XSSFRow row1 = sheet.getRow(1);
XSSFCell cell1 = row1.getCell(1);
cell1.setCellValue("Mahesh");
XSSFRow row2 = sheet.getRow(2);
XSSFCell cell2 = row2.getCell(1);
cell2.setCellValue("Ramesh");
OutputStream fos = new FileOutputStream(new File("D:\\test_new.xlsx"));
workbook.write(fos);
fis.close();
fos.close();
System.out.println("Done");
}
}
The image shows the different in size of two files.