Read an excel sheet in, process it and output it - java

I am playing around with the jexcel libary
I have tried to code a small program which does the following:
Read an xls File
Make some computaitons in the sheet and write it to another place
public class DataProcessor {
private String inputFile;
private String outputFile;
private Sheet sheet;
private Workbook w;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
sheet = w.getSheet(0);
} catch (BiffException e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Lolonator", 0);
workbook.createSheet("Lolonator123", 1);
workbook.copy(w);
workbook.write();
workbook.close();
}
public static void main(String[] args) throws IOException, WriteException {
ReadExcel test = new ReadExcel();
test.setInputFile("C:/Users/Desktop/sheet1.xls");
test.read();
System.out.println("####################################################");
System.out.println("File read!");
// Write
System.out.println("####################################################");
System.out.println("Start to write the file!");
WriteExcel out = new WriteExcel();
out.setOutputFile("C:/Users/Desktop/sheet2.xls");
out.write();
System.out.println("Please check the result file!");
}
}
However, this does not work. I do not get any output in my sheet, even though my program runs without exception to the end. I really appreciate your answer!!!

In your write function, you are using "inputFile" as parameter to File constructor but you are not initializing it after you create the out object.
So the following line in the write function
File file = new File(inputFile);
should be
File file = new File(outputFile);
Also are you sure that you do not see any errors after running this code. It should be throwing a null pointer exception.
Hope this helps...

Related

Update existing Excel file

I'm trying to update an existing Excel file. I used the code I saw here Writing to an Existing Excel File but I can't call the function from the main activity.
I tried to create a instance from the department.
It is my code of the class
public class ExceLJxL {
public ExceLJxL(){
}
public static void WriteFile(String path) throws BiffException, IOException, RowsExceededException, WriteException {
Workbook wb = Workbook.getWorkbook(new File(path));
WritableWorkbook copy = Workbook.createWorkbook(new File("D:\temp.xls"), wb);
WritableSheet sheet = copy.getSheet(1);
WritableCell cell;
Label l = new Label(1, 1, "");
cell = (WritableCell) l;
sheet.addCell(cell);
copy.write();
copy.close();
wb.close();
}
}
And here I call the function
ExceLJxL exceLJxL= new ExceLJxl();
exceLJxL.WriteFile( "path");
But he doesn't know it

Writing to file in recursion java

So i want my program to write all files containing ".txt" to "out.txt". But wr.close() ends my writer and it only writes the files from one folder and not from all. Need help.
import java.io.*;
public class Prv {
public static void main(String[] args) throws InterruptedException, IOException{
String a=".";
String b="D:\\JavaProjects\\Auditoriski\\.\\Out.txt";
Pomini(a,b);
}
public static void Pomini(String in, String out) throws IOException {
File file = new File(in);
BufferedWriter wr = new BufferedWriter(new FileWriter(out));
if(file.exists()) {
File[] subfiles = file.listFiles();
for(File f : subfiles) {
if(f.isDirectory()) {
Pomini(f.getAbsolutePath(), out );
}
if(f.getName().contains(".txt")) {
System.out.print(f.getName());
System.out.println();
wr.write(f.getName());
wr.newLine();
}
}
}
wr.close();
}
}
You just need to create BufferedWriter and close it outside of your Pomini method and pass it as a parameter.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(out));) {
Pomini(a, b, wr);
}
public static void Pomini(String in, String out, BufferedWriter wr) throws IOException {
File file = new File(in);
if(file.exists()) {
File[] subfiles = file.listFiles();
for(File f : subfiles) {
if(f.isDirectory()) {
Pomini(f.getAbsolutePath(), out, wr);
}
if(f.getName().contains(".txt")) {
System.out.print(f.getName());
System.out.println();
wr.write(f.getName());
wr.newLine();
}
}
}
}

How to read Excel sheet for specific rows and columns

I want to read Excel sheet from specific row number and only want some specific columns value. I tried lots of stuff, but I don't get proper output as expected.
Below is my code snippet:
public class ReadExcel {
File src=new File("F:\\ucd\\UAT_Patch_31012018.xlsx");
XSSFWorkbook wb;
XSSFSheet Sheet1;
FileOutputStream fileOut;
public void ReadExcel1() throws Exception{
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet Sheet1=wb.getSheetAt(0);
int rowcount=Sheet1.getPhysicalNumberOfRows();
int colcount=Sheet1.getRow(0).getPhysicalNumberOfCells();
for(int i=6;i<=9;i++){
for(int j=0;j<=rowcount;j++){
String testdata1=Sheet1.getRow(i).getCell(j).getStringCellValue();
System.out.println(testdata1);
}
}
}
public static void main(String args[]) throws Exception{
ReadExcel read=new ReadExcel();
read.ReadExcel1();
}
}
Excel file format:
File Name Target Server Target Path
abc/Abc.txt 10.0.43.101 /home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/pqr
xyz/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/xyz
I want to save my output in temp.txt file as below:
abc/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/pqr

Selenium Webdriver: Getting Nullpointerexception while reading an .xls file and unable to read it

I am trying to get data from the .xls file but when it tries to read sheet from .xls file, it throws nullpointerexception.
Exception in thread "main" java.lang.NullPointerException
at lib.ExcelDataConfig.getData(ExcelDataConfig.java:31)
at data.ReadData.main(ReadData.java:15)
Following is my code:
1. ReadData.java
public class ReadData {
/**
* #param args
*/
public static void main(String[] args) {
String path=System.getProperty("user.dir");
ExcelDataConfig dc=new ExcelDataConfig(path+"\\file\\TestData.xls");
String data=dc.getData("Sheet1", 0, 0);
System.out.println(data);
}
}
2.ExcelDataConfig.java
public class ExcelDataConfig {
HSSFWorkbook wb;
HSSFSheet sheet;
public ExcelDataConfig(String filepath){
try {
File fl=new File(filepath);
FileInputStream fis=new FileInputStream(fl);
HSSFWorkbook wb=new HSSFWorkbook(fis);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getData(String sheetName, int row, int col) {
sheet=wb.getSheet(sheetName);//throws exception at
String data=sheet.getRow(row).getCell(col).getStringCellValue();
return data;
}
}

How to save a file in java

I am trying to create a file from a log report. To save the file I've created a button. When the button is pushed, the following code is executed:
public void SAVE_REPORT(KmaxWidget widget){//save
try {
String content = report.getProperty("TEXT");
File file = new File("logKMAX.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} //SAVE_REPORT
I have no compilation errors, but there isn't any file saved.
Any idea on what might be wrong?
Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...
With the new file API, it is MUCH more simple:
public void saveReport(KmaxWidget widget)
throws IOException
{
final String content = report.getProperty("TEXT");
final Path path = Paths.get("logKMAX.txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE);
) {
writer.write(content);
writer.flush();
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class moveFolderAndFiles
{
public static void main(String[] args) throws Exception
{
File sourceFolder = new File("c:\\Audio Bible");
copyFolder(sourceFolder);
}
private static void copyFolder(File sourceFolder) throws Exception
{
File files[] = sourceFolder.listFiles();
int i = 0;
for (File file: files){
if(file.isDirectory()){
File filter[] = new File(file.getAbsolutePath()).listFiles();
for (File getIndividuals: filter){
System.out.println(i++ +"\t" +getIndividuals.getPath());
File des = new File("c:\\audio\\"+getIndividuals.getName());
Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}

Categories