Unable to insert values into existing work book [apache poi] - java

I would like to insert values into existing work book. Here the class that encapsulates this logic:
public class FormulaExtractor {
private String pathToExcelFile;
private XSSFWorkbook workbook;
private Map<Double, Formula> idFormular = new HashMap<>();
public FormulaExtractor(String pathToExcelFile) {
this.pathToExcelFile = pathToExcelFile;
try (FileInputStream fileInputStream = new FileInputStream(new File(pathToExcelFile))) {
this.workbook = new XSSFWorkbook(fileInputStream);
} catch (FileNotFoundException e) {
System.out.println("Cannot locate a xls file. Exception: " + e.toString());
} catch (IOException e) {
System.out.println("IO exception " + e.toString());
}
}
public void insertHumanReadableFormulas() throws IOException {
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
Cell cell = currentRow.createCell(CellReference.convertColStringToIndex("K"));
cell.setCellValue("Some dummy variable to test. ");
}
FileOutputStream fileOut = new FileOutputStream(new File(this.pathToExcelFile));
workbook.write(fileOut);
fileOut.close();
}
}
How do I use it:
public class App {
public static void main(String[] args) throws IOException {
final String pathToExcel = "some/path/some_excel.xlsx";
FormulaExtractor formulaExtractor = new FormulaExtractor(pathToExcel);
formulaExtractor.insertHumanReadableFormulas();
}
}
I don't get any exception or error. When I open my excel file, I simply cannot find values in a column "K". What am I doing wrong?

Related

I want to write the ouput of displayDirectoryContents to a excel sheet

I want to write the output of the displayDirectoryContents to a excel sheet
I have tried using the Apache POI method I want to get the output to a excel sheet
Folder and filename in one column and
the name of the files in another column
import statements
public class Excel {
private static String dest = "C:\\Users\\mahselva\\testexcel.xls";
private static HSSFWorkbook myWorkBook = new HSSFWorkbook();
private static HSSFSheet mySheet = myWorkBook.createSheet();
public static void excelLog(String filename, String message, int rowNum)
{
HSSFRow myRow = null;
HSSFCell myCell = null;
String excelData[][] = new String[1][2];
excelData[0][0] = filename;
excelData[0][1] = message;
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 2; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[0][cellNum]);
}
try {
FileOutputStream out = new FileOutputStream(dest);
myWorkBook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File currentDir = new File("C:\\OracleATS\\openScript"); // current
directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
int i = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println("Folder"
+path.getFileName().toString());
excelLog("Folder",path.getFileName().toString(),i);
i++;
displayDirectoryContents(file);
} else {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println(path.getFileName().toString());
excelLog("File",path.getFileName().toString(),i);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want two columns in an excel sheet with column 1 containing File or
Folder and column 2 containing the name of the file/folder
eg
File books.xml
Folder Script
Thus i want to write the output to the excel sheet
i am using the function excel log to write to the output screen
I use this to write to an excel - however I make it .csv format, not xls. Therefore this might not be what you need, but it's still partially useful as it's writing in a file that can be opened by excel efortlessly.
public static void printAtFile(String filename, String header, String content[])
{
filename+=".csv";
System.out.println("Start creating file "+filename);
PrintWriter writer = null;
try {
writer = new PrintWriter(filename);
writer.println(header);
for(String u:content)
writer.println(u);
writer.close();
} catch (Exception ex) {
System.out.println("Error while writing at file "+filename);
}
}

Exporting automated value to excel file in java

I am using selenium webdriver in eclipse with Java for a project at work. I am in need of exporting a value to an excel file. I am able to write to an excel file but am unable to export the specific value to the excel file.
Here is the automation process for getting the value:
public void AbbeyNational (String AbbeyNationalURL, String AN_AccCookiesButton, String AN_MortgageTabButton, String AN_ExistingCustomerButton, String AN_FollowRateButton, String AN_SVRButton, String AN_RateFld)throws InterruptedException {
driver.get(AbbeyNationalURL);
driver.findElement(By.xpath(AN_AccCookiesButton)).click();
driver.findElement(By.linkText(AN_MortgageTabButton)).click();
driver.findElement(By.xpath(AN_ExistingCustomerButton)).click();
driver.findElement(By.xpath(AN_FollowRateButton)).click();
driver.findElement(By.xpath(AN_SVRButton)).click();
String a = driver.findElement(By.cssSelector(AN_RateFld)).getText();
String AN_Rate = a.substring(54,58);
System.out.println(AN_Rate);
}
The 'AN_Rate' variable holds the value after automation.
The value prints to the console but I need the value to be exported to the excel file with the use of automation. Can anyone help me with this?
Additionally, here is my code for writing to an excel file:
public void writeToExcel(String AN_Rate) throws IOException{
File file = new File(filePath+"\\"+fileName);
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet Sheet0 = IRWorkbook.createSheet();
Sheet0.createRow(0).createCell(0).setCellValue(AN_Rate);
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can use this code for large set of data :
public class ExcelWriter {
// LinkedHashMap to maintain the insertion order
public static Map<String, String> dataMap = new LinkedHashMap<>();
public static String filePath = "D:\\ECLIPSE-WORKSPACE\\playground\\src\\main\\resources";
public static String fileName = "demo-data";
public static void main(String[] args) throws IOException {
String AN_Rate = "Data-1";
String BN_Rate = "Data-2";
String CN_Rate = "Data-3";
dataMap.put("AN_Rate", AN_Rate);
dataMap.put("BN_Rate", BN_Rate);
dataMap.put("CN_Rate", CN_Rate);
writeToExcel(dataMap, filePath, fileName);
}
public static void writeToExcel(Map<String, String> dataMap, String filePath, String fileName) throws IOException {
File file = new File(filePath + "\\" + fileName + ".xlsx");
if (file.exists()) {
file.delete();
}
file.createNewFile();
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet sheet = IRWorkbook.createSheet();
List<String> headers = dataMap.keySet().stream().collect(Collectors.toList()); // all key values in a list
List<String> data = new ArrayList<>(dataMap.values()); // all data in a list
setHeadersAndFillData(sheet, headers, data); // filling excel sheet with headers and corresponding data
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void setHeadersAndFillData(XSSFSheet sheet, List<String> headers, List<String> data) {
int headersSize = headers.size();
int dataSize = headers.size();
Row headerRow = sheet.createRow(0);
Row dataRow = sheet.createRow(1);
setCells(headers, headersSize, headerRow);
setCells(data, dataSize, dataRow);
}
private static void setCells(List<String> cellData, int headersSize, Row row) {
for (int rn = 0; rn < headersSize; rn++) {
row.createCell(rn).setCellValue(cellData.get(rn));
}
}
}
Just edit your method writeToExcel with :
Replace :File file = new File(filePath+"\\"+fileName);
with added file extention
File file = new File(filePath+"\\"+fileName + ".xlsx");
and than the value will be exported to excel file.
And if there is large set of data than you should store all values in a static map and than export all values to excel at once.

how to load data from database to excel sheet

I need to load data from database to excel sheet. so when I run the code throw this exception.
This is what i am working with so far.
database table name is pettycash so I need to load data from this table.
private void excelTest(ActionEvent event) {
try {
String cococo = "select * from pettycash";
ResultSet rs = database.DB_Connector.search(cococo);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("pettycash");
XSSFRow Header = sheet.createRow(0);
Header.createCell(0).setCellValue("Petty ID");
Header.createCell(1).setCellValue("pettycash_static_ammount");
Header.createCell(2).setCellValue("pettycash_balance");
Header.createCell(3).setCellValue("pettygiv_Date");
Header.createCell(4).setCellValue("pettycash_status");
Header.createCell(5).setCellValue("Rider_idRider");
int index = 1;
while (rs.next()) {
XSSFRow row = sheet.createRow(index);
row.createCell(0).setCellValue(rs.getString("idpettycash"));
row.createCell(1).setCellValue(rs.getString("pettycash_static_ammount"));
row.createCell(2).setCellValue(rs.getString("pettycash_balance"));
row.createCell(3).setCellValue(rs.getString("pettygiv_Date"));
row.createCell(4).setCellValue(rs.getString("pettycash_status"));
row.createCell(5).setCellValue(rs.getString("Rider_idRider"));
index++;
}
FileOutputStream fileout = new FileOutputStream("petycash.xlsx");
wb.write(fileout);
fileout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Look at this solution using MemPOI
private void excelTest(ActionEvent event) {
try {
String cococo = "select * from pettycash";
PreparedStatement prepStmt = database.DB_Connector.preparedStatement(cococo);
File file = new File("petycash.xlsx");
new MempoiBuilder()
.setFile(file)
.addMempoiSheet(new MempoiSheet(prepStmt))
.build()
.prepareMempoiReportToFile()
.get();
} catch (Exception e) {
e.printStackTrace();
}
}
You can use this library to perform what you are trying to do manually. One line of code:
writer.writeAll(rs, includeHeaders);

Pass login data from excel file using selenium java. not able to use getRow() , getCell()

I want to pass username and password in a webpage from excel sheet. help me to get the out put.
error is display as red underline in getRow(), getColumn(), getCell() etc.
This is my java file:
public class NewTest_tstng_excel {
public WebDriver driver;
public static XSSFSheet excelSheet;
public void login() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
}
#BeforeClass
public void testSetup() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
//wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider="empLogin")
public void VerifyInvalidLogin(String userName, String password) {
driver.get("URL goes here");
driver.findElement(By.id("UserName")).sendKeys(userName);
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
driver.findElement(By.id("Password")).sendKeys(password);
driver.findElement(By.id("btnLogin")).submit();
}
#DataProvider(name="empLogin")
public Object[][] loginData() {
Object[][] arrayObject = getExcelData("E:\\disha.shah\\myWork\\sele_proj\\FAM_Excel data\\src\\DataFile\\Book1.xlsx","Sheet1");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fs);
//Workbook wb = Workbook.getWorkbook(fs);
//Sheet sh = wb.getSheet(sheetName);
excelSheet = workBook.getSheet("Sheet1");
int totalNoOfCols = excelSheet.getColumns();
int totalNoOfRows = excelSheet.getRows();
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i= 1 ; i < totalNoOfRows; i++) {
for (int j=0; j < totalNoOfCols; j++) {
arrayExcelData[i-1][j] = excelSheet.getCell(j, i).getContents();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
in excel: there is 2 column containing username and password.
See if getRow is null.
You can do createRow().
If in the excel you don't use the row you need, you will have to create a new row, otherwise you use getRow if the row is already in use!

Java List to Excel Columns

Correct me where I'm going wrong.
I'm have written a program in Java which will get list of files from two different directories and make two (Java list) with the file names. I want to transfer the both the list (downloaded files list and Uploaded files list) to an excel.
What the result i'm getting is those list are transferred row wise. I want them in column wise.
Given below is the code:
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\report\\02_Download\\10252013");
Path dispatchPath = Paths.get("E:\\report\\01_Dispatch\\10252013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10252013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List> recordToAdd = new ArrayList<>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
F f = new F();
f.CreateExcelFile(recordToAdd);
f.createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<List> l1) throws Exception {
try {
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2 = l1.get(j);
for (int k = 0; k < l2.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
} finally {
}
}
}
(The purpose is to verify the files Downloaded and Uploaded for the given date)
Thanks.
If you want to access/build the worksheet in columns instead of rows, you need to change the worksheet accessing code.
Snipped out from your existing code, here are the key functions:
Row row = firstSheet.createRow( rowNum);
Cell cell = row.createCell( colNum);
cell.setCellValue( value);
You need to rearrange those loops to output your data in a column-wise fashion.
Thanks for the suggestions.. I have modified my program and uploaded with the solution.
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\Download\\10292013");
Path dispatchPath = Paths.get("E:\\Dispatch\\10292013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
/* List all files*/
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10292013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<String>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List<String>> recordToAdd = new ArrayList<List<String>>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
CreateExcelFile(headerRow, download, upload);
createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<String> headers, List<String> down, List<String> up) throws Exception {
try {
Row row = firstSheet.createRow((short)(rownum++));
for(int i = 0;i < headers.size();i++) {
Cell cell = row.createCell(i);
cell.setCellValue(headers.get(i));
}
for (int j = 0; j < down.size(); j++) {
row = firstSheet.createRow((short)(rownum++));
Cell cell = row.createCell(0);
cell.setCellValue(down.get(j));
if(up.size() > j) {
cell = row.createCell(1);
cell.setCellValue(up.get(j));
}
}
} catch (Exception e) {
} finally {
}
}
}

Categories