How to set the excel file's visibility to true - java

I am creating a new excel file using Apache POI and I would like to set the file's visibility to true. What function or code do I use to show the file after I create it using Apache POI rather than just saving it in a directory?
I have tried the following line of code which is similar to what we use in LotusScript but I got a "Instance member VISIBLE does not exist" error on that line.
ExcelApplication.Visible = True
Below is the code I'm using to write the excel file, which does work correctly as it saves the file in the directory I specified in the 'fileName'.
public boolean writeExcelFile(String fileName) {
try {
//Auto fit content
for(int i = 0; i < 20; i++) {
this.wbSheet.autoSizeColumn((short)i);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(fileName);
this.wb.write(fileOut);
fileOut.close();
} catch(Exception ex) {
ex.printStackTrace();
return(false);
}
return(true);
}
I expect the excel file to be created and opened rather than saved on the computer.

The VBA code line ExcelApplication.Visible = True, where ExcelApplication would must be an Application object, can only work because VBA works directly together with the Microsoft Office applications. This is not what apache poi is doing. Apache poi's goal is creating files in the Microsoft Office file formats. Neither it needs any installed Microsoft Office application nor it tries to interact with those applications.
So after apache poi is ready with it's work, then you always will get a file in the appropriate Microsoft Office file format. The only thng you could do then is opening that file using java.awt.Desktop. For example:
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
Complete Example:
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.GregorianCalendar;
import java.awt.Desktop;
class CreateExcelAndOpenFile {
private Workbook workbook;
private Sheet sheet;
public CreateExcelAndOpenFile() {
this.workbook = new XSSFWorkbook();
this.sheet = this.workbook.createSheet();
}
public Workbook getWorkbook() {
return this.workbook;
}
public boolean writeDataInSheet(Object[][] data, String[] columnCellTypes, CellStyle[] columnCellStyles) {
try {
FormulaEvaluator formulaEvaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
for (int r = 0; r < data.length; r++) {
Row row = this.sheet.createRow(r);
for (int c = 0; c < data[0].length; c++) {
Cell cell = row.createCell(c);
if (r == 0) {
cell.setCellValue((String)data[r][c]); // header row, all String
cell.setCellStyle(columnCellStyles[c]);
} else if ("number".equals(columnCellTypes[c]) && data[r][c] instanceof Double) {
cell.setCellValue((Double)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("date".equals(columnCellTypes[c]) && data[r][c] instanceof GregorianCalendar) {
cell.setCellValue((GregorianCalendar)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("text".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellValue((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("formula".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellFormula((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
formulaEvaluator.evaluateFormulaCell(cell);
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean writeExcelFile(String fileName) {
try (FileOutputStream fileOut = new FileOutputStream(fileName) ) {
// auto fit content
int columnsCountInHeaderRow = this.sheet.getRow(0).getLastCellNum();
for(int i = 0; i < columnsCountInHeaderRow; i++) {
this.sheet.autoSizeColumn((short)i);
}
// write the output to a file
this.workbook.write(fileOut);
this.workbook.close();
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
String fileName = "./Excel.xlsx";
CreateExcelAndOpenFile application = new CreateExcelAndOpenFile();
Object[][] data = new Object[][] {
new Object[] {"Name", "Value", "Date", "Formatted value", "Formula"},
new Object[] {"Lorem", 123.456789, new GregorianCalendar(2019, 0, 15), 123.456789, "ROUND(B2,2)"},
new Object[] {"Ipsum", 1234.56789, new GregorianCalendar(2019, 5, 15), 1234.56789, "ROUND(B3,2)"}
};
String[] columnCellTypes = new String[]{"text", "number", "date", "number", "formula"};
DataFormat dataFormat = application.getWorkbook().createDataFormat();
CellStyle dateStyle = application.getWorkbook().createCellStyle();
dateStyle.setDataFormat(dataFormat.getFormat("DDDD, MMMM, DD, YYYY"));
CellStyle numberStyle = application.getWorkbook().createCellStyle();
numberStyle.setDataFormat(dataFormat.getFormat("#,##0.00 \" Coins\""));
CellStyle[] columnCellStyles = new CellStyle[]{null, null, dateStyle, numberStyle, null};
boolean success = application.writeDataInSheet(data, columnCellTypes, columnCellStyles);
System.out.println(success);
if (success) {
success = application.writeExcelFile(fileName);
System.out.println(success);
if (success) {
success = application.openExcelFile(fileName);
System.out.println(success);
if (success) {
System.out.println("Done successfully");
}
}
}
}
}

Related

How to read an Excel file in java with DataProvider

I have trouble reading the information in an Excel file to introduce and test with selenium. But the result always NullPoInterException. I tried to change the link in the Excel file. Here’s the 2-part code.
public class TestProviderII {
public static void main(String[] args) {
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
testData(url, "SheetOne");
}
public static void testData(String url, String sheet) {
ExcelUtils excelUtils = new ExcelUtils(url, sheet);
int rowCount = excelUtils.getRowCount();
int colCount = excelUtils.getColCount();
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
String cellData = excelUtils.getCellDataString(i, j);
System.out.println("Data : " + cellData);
}
}
}
}
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
static XSSFWorkbook workbook;
static XSSFSheet sheet;
public ExcelUtils(String workBook, String sheetName) {
try {
workbook = new XSSFWorkbook(workBook);
sheet = workbook.getSheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getRowCount() {
int rowCount = 0;
try {
rowCount = sheet.getPhysicalNumberOfRows();
System.out.println("No of Row : " + rowCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return rowCount;
}
public static int getColCount() {
int colCount = 0;
try {
colCount = sheet.getRow(0).getPhysicalNumberOfCells();
System.out.println("No of Column" + colCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return colCount;
}
public static String getCellDataString(int rowNum, int colNum) {
String cellData = "";
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getStringCellValue();
System.out.println("Data Cell : " + cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
public static Double getCellDataNumber(int rowNum, int colNum) {
double cellData = 0;
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
System.out.println(cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
}
And the result is NullPointerException
null
null
null
null
java.lang.NullPointerException
at test.ExcelUtils.getRowCount(ExcelUtils.java:23)
at test.TestProviderII.testData(TestProviderII.java:12)
at test.TestProviderII.main(TestProviderII.java:7)
java.lang.NullPointerException
at test.ExcelUtils.getColCount(ExcelUtils.java:36)
at test.TestProviderII.testData(TestProviderII.java:13)
at test.TestProviderII.main(TestProviderII.java:7)
Process finished with exit code 0
Why the result nullPointerException despite I did exactly what said?
And I changed the Excel file link and the result is the same.
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
String url = "src\\test\\resources\\dataProvider.xlsx";
String url = "C:\\Selenuim\\demoApplication\\src\\test\\resources\\dataProvider.xlsx
Change below line:
testData(url, "SheetOne");
to:
testData(url, "Sheet1");
Assuming the sheet looks like below in your excel file:
Also ensure, there is some data in your excel sheet. I ran your code by just changing to Sheet1. And it worked see below:
Excel sheet:
Console Output:
No of Column3
Data Cell : d
Data : d
Data Cell : e
Data : e
Data Cell : f
Data : f

PrintWriter printing "line.separator" twice in file

I have a method called saveAgendaDataArrayList() which is suposed to save the data from an ArrayList in a TXT file as following.
public void saveAgendaDataArrayList(String path, ArrayList<Contact> agendaDataArrayList) {
try {
if(agendaDataArrayList!=null) {
File file = new File(path);
PrintWriter p = new PrintWriter(file);
int count = agendaDataArrayList.size();
for(int i=0; i<count; i++) {
Contact temp = new Contact();
temp = agendaDataArrayList.get(i);
p.println(temp.getIdAdress()+";"+temp.getContactType()+";"+temp.getName()+";"+temp.getBirthdayDay()+
";"+temp.getBirthdayMonth()+";"+temp.getBirthdayYear()+";"+temp.getTel1()+";"+temp.getTel2()+
";"+temp.getNeigborhood()+";"+temp.getAddress()+";"+temp.getCep()+";"+temp.getEmail()
+";"+temp.getOtherInformation()+";"+temp.getCreationDate()+";");
}
p.close();
} else {
File file = new File(path);
PrintWriter p = new PrintWriter(file);
p.print("empty agenda");
p.close();
}
} catch (IOException e) {
e.printStackTrace();
}
However, when it runs, I have some new lines coming from I don't know where. Look below.
1;1;Guilhermee;00;00;;8666666;;sem bairro;;;;;12-09-2019 04:45:47;
2;1;Gabriella;00;00;;;;Morada do Sol;;;;;12-09-2019 04:45:57;
3;1;joao;00;00;;;;sem bairro;;;;;12-09-2019 05:38:13;
4;1;lua;00;00;;;;sem bairro;;;;;12-09-2019 06:11:15;
5;1;roberto;00;00;;;;sem bairro;;;;;12-09-2019 06:12:22;
6;1;joquina;00;00;;;;Monte Verde;;;;;12-09-2019 07:38:30;
7;1;luan silva;00;00;;;;sem bairro;;;;;12-09-2019 07:40:07;
8;1;manoel;00;00;;89898989;;sem bairro;asdasd;;;;12-09-2019 07:44:44;
9;1;joana;19;01;1954;;;Cidade Jardim;;;;;12-09-2019 07:48:03;
10;1;mariana;00;00;;;;sem bairro;;;;;12-09-2019 07:57:43;
11;1;agoradeucerto;00;00;;;;Morros;;;;;12-09-2019 08:01:46;
12;1;mais uma tentativa;00;00;;;;sem bairro;;;;;12-09-2019 08:43:19;
I'd like to have an output file as above, but without the empty lines.
I tried to see if the same would happen in console with the method System.out.println(), and it happened there too.
Looking in a text file editor, the Notepad, I noticed there are some LF mixed with CR LF in the end of lines.
I've reviewed the Contact class and all seems to be right.
So, what could I do to reach that result and avoid those empty lines, and why only the last line is in the correct place?
Thank you for your time.
EDIT 1 - The input method
Here is the input method. There are 2 ways to add the data into agendaDataArrayList. The first one is through reading a txt file (1st method) and the second one, through an input interface (2nd method).
1st method
public ArrayList<Contact> getAgendaDataArrayList(String path) {
try {
FileReader reader = new FileReader(path);
Scanner scanner1 = new Scanner(reader);
scanner1.useDelimiter("\r\n|\n");
int count = 0;
while(scanner1.hasNext()) {
scanner1.next();
count++;
}
System.out.println(count);
scanner1.close();
reader.close();
ArrayList<Contact> agendaDataArrayList = new ArrayList<Contact>();
FileReader reader2 = new FileReader(path);
Scanner scanner2 = new Scanner(reader2);
scanner2.useDelimiter(";");
for(int i=0; i<count; i++) {
Contact temp = new Contact();
temp.setIdAdress(scanner2.next()); //[0] id
temp.setContactType(scanner2.next()); //[1] type
temp.setName(scanner2.next()); //[2] name
temp.setBirthdayDay(scanner2.next()); //[3] birthdayDay
temp.setBirthdayMonth(scanner2.next()); //[4] birthdayMonth
temp.setBirthdayYear(scanner2.next()); //[5] birthdayYear
temp.setTel1(scanner2.next()); //[6] tel1
temp.setTel2(scanner2.next()); //[7] tel2
temp.setNeigborhood(scanner2.next()); //[8] neighborhood
temp.setAddress(scanner2.next()); //[9] address
temp.setCep(scanner2.next()); //[10] cep
temp.setEmail(scanner2.next()); //[11] email
temp.setOtherInformation(scanner2.next()); //[12] other information
temp.setCreationDate(scanner2.next()); //[13] creation date
agendaDataArrayList.add(temp);
}
scanner2.close();
reader2.close();
return agendaDataArrayList;
} catch (IOException e) {
e.printStackTrace();
ArrayList<Contact> agendaDataArrayList = new ArrayList<Contact>();
return agendaDataArrayList;
}
}
2nd method
public void saveActionButton() {
Date creationDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Contact newContact = new Contact();
newContact.setIdAdress(mainApp.getNextIdAddress());
if(typeChoiceBox.getValue()==null) {
newContact.setContactType("1");
} else {
newContact.setContactType(typeChoiceBox.getValue());
}
if(nameTextField.getText()==null) {
newContact.setName("sem nome");
} else {
newContact.setName(nameTextField.getText());
}
if(dayChoiceBox.getValue()==null) {
newContact.setBirthdayDay("00");
}else {
newContact.setBirthdayDay(dayChoiceBox.getValue());
}
if(monthChoiceBox.getValue()==null) {
newContact.setBirthdayMonth("00");
}else {
newContact.setBirthdayMonth(monthChoiceBox.getValue());
}
if(yearTextField.getText()==null) {
newContact.setBirthdayYear("0000");
}else {
newContact.setBirthdayYear(yearTextField.getText());
}
if(tel1TextField.getText()==null) {
newContact.setTel1("sem número");
}else {
newContact.setTel1(tel1TextField.getText());
}
if(tel2TextField.getText()==null) {
newContact.setTel2("sem número");
}else {
newContact.setTel2(tel2TextField.getText());
}
if(neighborhoodChoiceBox.getValue()==null) {
newContact.setNeigborhood("sem bairro");
} else {
newContact.setNeigborhood(neighborhoodChoiceBox.getValue());
}
if(addressTextField.getText()==null) {
newContact.setAddress("sem endereço");
} else {
newContact.setAddress(addressTextField.getText());
}
if(cepTextField.getText()==null) {
newContact.setCep("sem CEP");
}else {
newContact.setCep(cepTextField.getText());
}
if(emailTextField.getText()==null) {
newContact.setEmail("sem e-mail");
} else {
newContact.setEmail(emailTextField.getText());
}
if(otherInfoTextArea.getText()==null) {
newContact.setOtherInformation("sem mais informações");
}else {
newContact.setOtherInformation(otherInfoTextArea.getText());
}
newContact.setCreationDate(formatter.format(creationDate).toString());
mainApp.addContactToAgendaDataArrayList(newContact);
mainApp.refreshFullContentInMainLayout();
mainApp.saveFile();
Stage stage = (Stage) saveButton.getScene().getWindow();
stage.close();
}
}
Compare the first method output of the entries with id address 12 and the other ones that have new lines before them.
It is possible that some data are inserted on windows (therefore the CR LF whitespaces) and some on the unix system (which uses only LF). Anyway, it seems tha data itself contains new line marks, the PrinterWriter works as you would like.
A small test:
import java.util.ArrayList;
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
ArrayList<Contact> list = new ArrayList<>();
list.add(new Contact());
list.add(new Contact());
list.add(new Contact());
list.add(new Contact());
list.add(new Contact());
try {
File file = new File("output.txt");
PrintWriter p = new PrintWriter(file);
int count = list.size();
for (int i = 0; i < count; i++) {
Contact temp = list.get(i);
p.println(temp.getFavColour() + ";" + temp.getSurname() + ";" + temp.getName() + ";");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static class Contact {
public String getName() {
return "John";
}
public String getSurname() {
return "Black";
}
public String getFavColour() {
return "red";
}
}
}

Why I cant return the value in the method in selenium?

I already create a method that can return the value in the excel but when i run the main scripts that call the method, the value cannot be return. Maybe there is a problems with my code but i do not know which part that i need to fix.
This is the script that call the method.
GetExcel res = new GetExcel();
String maker = res.getExcel("IS Maker Username");
GetExcel res1 = new GetExcel();
String passMaker = res1.getExcel("IS Maker Password");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#name='userName']")));
driver.findElement(By.xpath("//input[#name='userName']")).click();
driver.findElement(By.xpath("//input[#name='userName']")).sendKeys(maker);
driver.findElement(By.xpath("//input[#name='password']")).click();
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(passMaker);
driver.findElement(By.name("submitLogin")).click();
This is the method function
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
#Test
public class GetExcel {
private XSSFWorkbook wb;
public String getExcel(String getName) throws IOException {
File src = new File("C:\\selenium\\ExcelData\\TestData.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
XSSFSheet sh1 = wb.getSheetAt(0);
String getValue = null;
String value = null;
for (int i = 1; i<=1000; i++) {
if(sh1.getRow(i).getCell(0) != null)
{
getValue = sh1.getRow(i).getCell(0).getStringCellValue();
}
if(getValue != null) {
if(getValue.contains(getName)) {
if(sh1.getRow(i).getCell(1) != null)
{
value = sh1.getRow(i).getCell(1).getStringCellValue();
}
System.out.println(value);
fis.close();
break;
}
}
}
return value;
}
}
The method function was imported from different packages
1.Your code will always return null value because you are comparing cell value with excel sheet_Name.
2.While you are returning value your second column it should not be empty.
3.If you are trying to fetch any value that is number,you should put ' before number in cell like '12345
Modified your code Now try.
public String getExcel(String getName) throws IOException {
File src = new File("C:\\selenium\\ExcelData\\TestData.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
XSSFSheet sh1 = wb.getSheet(getName);
String getValue = null;
String value = null;
int number=sh1.getLastRowNum()+1;
System.out.println("Total used rows :" + number);
for (int i = 1; i<number; i++) {
if(sh1.getRow(i).getCell(0) != null)
{
getValue = sh1.getRow(i).getCell(0).getStringCellValue();
}
if(getValue != null) {
if(!getValue.contains(getName)) {
if(sh1.getRow(i).getCell(1) != null)
{
value = sh1.getRow(i).getCell(1).getStringCellValue();
}
System.out.println(value);
fis.close();
break;
}
}
}
return value;
}
Here is the main function call.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
GetExcel res = new GetExcel();
String maker = res.getExcel("IS Maker Username");
System.out.println("User :" + maker);
GetExcel res1 = new GetExcel();
String passMaker = res1.getExcel("IS Maker Password");
System.out.println("Password :" + passMaker);
}
Please let me know whether it works for you.

Apache POI event API Update existing Excel sheet

I have large excel file with several worksheets.
I want to process just one sheet in file...Read value from two columns and update two columns.
Using this code, I am able to read data from sheet.But unable to figure out, how to save output back.
public class ExcelFunctions {
private class ExcelData implements SheetContentsHandler {
private Record rec ;
public void startRow(int rowNum) {
rec = new Record();
output.put("R"+rowNum, rec);
}
public void endRow(int rowNum) {
}
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
int thisCol = (new CellReference(cellReference)).getCol();
if(thisCol==7){
try {
rec.setK1(formattedValue);
} catch (Exception e) {
}
}
if(thisCol==8){
try {
rec.setK2(formattedValue);
} catch (Exception e) {
}
}
if(thisCol == 27){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 27
}
if(thisCol == 28){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 28
}
}
public void headerFooter(String text, boolean isHeader, String tagName) {
}
}
///////////////////////////////////////
private final OPCPackage xlsxPackage;
private final Map<String, Record> output;
public ExcelFunctions(OPCPackage pkg, Map<String, Record> output) {
this.xlsxPackage = pkg;
this.output = output;
}
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler,
InputStream sheetInputStream)
throws IOException, ParserConfigurationException, SAXException {
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(
styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
public void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
boolean found = false;
while (iter.hasNext() && !found) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
if(sheetName.equals("All Notes") ){
processSheet(styles, strings, new ExcelData(), stream);
found = true;
}
stream.close();
}
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
File xlsxFile = new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm");
if (!xlsxFile.exists()) {
System.err.println("Not found or not a file: " + xlsxFile.getPath());
return;
}
// The package open is instantaneous, as it should be.
OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ_WRITE);
Map<String, Record> output = new HashMap<String, Record>();
ExcelFunctions xlFunctions = new ExcelFunctions(p, output);
xlFunctions.process();
p.close();
if (output != null){
for(Record rec : output.values()){
System.out.println(rec.full_key());
}
}
}
}
File is very large and I only want to use Event API.
I have successfully tested Using this code.
But this loads Whole file in memory(causing application to crash)...While I only need to edit One sheet.
public static void saveToExcel(String ofn, Map<String, Record> data) {
FileInputStream infile;
try {
infile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm"));
XSSFWorkbook workbook = new XSSFWorkbook (infile);
XSSFSheet sheet = workbook.getSheet("All Notes");
for(Record rec : output.values()){
Row dataRow = rec.getRow(rev.getRownum-1);
setCellValue(dataRow, 26, "SomeValue");
setCellValue(dataRow, 27, "SomeValue");
}
FileOutputStream out = new FileOutputStream(new File(ofn));
workbook.write(out);
infile.close();
out.close();
workbook.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void setCellValue(Row row,int col, String value){
Cell c0 = row.getCell(col);
if (c0 == null){
c0 = row.createCell(col);
}
c0.setCellValue(value);
}
I don't think there is anything provided in POI out of the box which allows to do that.
Therefore you might be better off doing this by unzipping the XLSX/XLSM file (they are actually a bunch of xml-files inside a zip) and reading the xml-files as text-files or with a normal XML Parser so that you can easily write out the changed file again to produce the XLSX/XLSM file again.

how to get data from excel file?

Actually i am working on a java program that extracts data from an Excel file,
and i am using the POI Library, as a matter of fact i must specify the type of every extracted value, but the file contains a huge number of data with different types,
So i am asking if there is another way to get all the data as a string.
Thank you.
Best regards
package DAO;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadExcelFile {
public static void main(String[] args) {
String fileName = "C:\\Users\\marrah\\Desktop\\TRIAL FILE1.xls";
Vector dataHolder = ReadCSV(fileName);
printCellData(dataHolder);
}
public static Vector ReadCSV(String fileName) {
Vector cellVectorHolder = new Vector();
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
return cellVectorHolder;
}
private static void printCellData(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
Object stringCellValue="";
stringCellValue =cellStoreVector.get(j).toString();
System.out.print(stringCellValue.toString()+"\t");
}
}
}
}
I have a unit-test where I use the following to extract all text from an Excel file without any of the formatting, for some use-cases this might be quicker than iterating over all the elements one-by-one:
private POITextExtractor extractText(File file) throws IOException {
InputStream inp = null;
try {
inp = new PushbackInputStream(
new FileInputStream(file), 8);
if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return createExtractor(new POIFSFileSystem(inp));
}
throw new IllegalArgumentException("Your File was neither an OLE2 file, nor an OOXML file");
} finally {
if(inp != null) inp.close();
}
}
private static POITextExtractor createExtractor(POIFSFileSystem fs) throws IOException {
return createExtractor(fs.getRoot(), fs);
}
private static POITextExtractor createExtractor(DirectoryNode poifsDir, POIFSFileSystem fs) throws IOException {
for(Iterator<Entry> entries = poifsDir.getEntries(); entries.hasNext(); ) {
Entry entry = entries.next();
if(entry.getName().equals("Workbook")) {
{
return new ExcelExtractor(poifsDir, fs);
}
}
}
throw new IllegalArgumentException("No supported documents found in the OLE2 stream");
}
private String assertContains(File file, String... contents) throws IOException {
assertTrue(file.exists());
POITextExtractor extractor = extractText(file);
assertNotNull(extractor);
String str = extractor.getText();
for(String s : contents) {
assertTrue("Did expect to find text '" + s + "' in resulting Excel file, but did not find it in str: " + str, str.contains(s));
}
return str;
}
You can create a common function to use on every cell when you runs thru each row, which validates the data type and then retrieves it in your preferred format. So you move row to row and, for each cell you call something like:
private static String getCellvalue(HSSFRow poiRow, int intColActual) {
if (poiFilaActual != null && poiRowActual.getLastCellNum() >= (short) intColActual) {
HSSFCell cell = poiRowActual.getCell(intColActual);
if (cell != null) {
if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
return cell.getRichStringCellValue().toString();
} else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
return new String( (cell.getBooleanCellValue() == true ? "true" : "false") );
} else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
return "";
} else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
if(HSSFDateUtil.isCellDateFormatted(cell)){
return ( new SimpleDateFormat("dd/MM/yyyy").format(cell.getDateCellValue()) );
}else{
return new BigDecimal(cell.getNumericCellValue()).toString();
}
}
}
}
return null;
}

Categories

Resources