I have two queries as below :-
1) Below is my code to find the total disk space, free and used disk space in my local machine. I want to export these values in a newly created excel sheet under three columns Total Disk Space, Free DiskSpace and UsedDiskSpace.
But in my below code I am able to a create excel sheet under C:\ location but I am not able to set the values of my excel sheet columns to the ones calculated and stored under Total diskspace, FreeDiskSpace and UsedDiskSpace variables. Can anyone suggest me how can I modify my below code to set the excel sheet column values to capacity,Free space and used space variable values etc.
2) How can I convert this code into a .bat executable file so that it can be executed on double click and there is no need to execute the entire code through IDE. Some examples will help!!
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="C:/NewExcelFile.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("C:");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell((short) 0).setCellValue(capacity);
rowhead.createCell((short) 1).setCellValue(freespace);
rowhead.createCell((short) 2).setCellValue(usedspace);
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
}} catch ( Exception ex ) {
System.out.println(ex);
}
}}
Remove
rowhead.getCell(1).setCellValue(capacity);
line.It gives NullPointerException error and don't use createCell(short) it is deprecated method so please remove short type cast.
Here is my code
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="/home/likewise-open/EZDI-DOMAIN/cshah/Desktop/NewExamle.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("/home/likewise-open/EZDI-DOMAIN/cshah/Desktop");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)i);
//rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell(0).setCellValue(capacity);
rowhead.createCell(1).setCellValue(freespace);
rowhead.createCell(2).setCellValue(usedspace);
}
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();} catch ( Exception ex ) {
ex.printStackTrace();
}
}}
Related
I need to read cells from XLSX. I use Apache POI, but I don't know what the mistake is.
This is my code:
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class miniwolfi {
public static void main(String[] args) throws IOException {
File excel = new File("/tmp/table.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
double result = wb.getSheetAt(0).getRow(0).getCell(0).getNumericCellValue();
System.out.println(result);
fis.close();
}
}
And the error
java.io.FileNotFoundException: /tmp/таблица.xlsx (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at miniwolfi.main(miniwolfi.java:17)
Maybe mistake is the way to XLSX. How can I fix this?
Check if the file is xlsx or xls files first, and you have permissions,
Your error is the file is not found
I would write it as follow and use try-with-resources
File excel = new File("/tmp/table.xlsx");
try(FileInputStream fis = new FileInputStream(excel);){
XSSFWorkbook wb = new XSSFWorkbook(fis);
double result = wb.getSheetAt(0).getRow(0).getCell(0).getNumericCellValue();
System.out.println(result);
}
I want to get the image address of first result from google and save into excel sheet. I use apache poi library for reading excel sheet.
I want src data as per image. and other thing is that src data in image is not full. We have to double click on it to copy whole data.
I tried jsoup library and but not getting correct result. Please suggest me any change.
package com.uc.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class ReadExcelFileDemo {
public static void main(String...args) throws IOException {
final String GOOGLE_SEARCH_URL ="https://www.google.com/search?q=";
//https://www.google.co.in/search?q=usa&hl=en&tbm=isch
FileInputStream fis=new FileInputStream(new File("C:\\users\\hvt\\desktop\\country.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0); //creating a Sheet object to retrieve object
Iterator<Row> itr = sheet.iterator(); //iterating over excel file
while (itr.hasNext())
{
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator(); //iterating over each column
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t\t");
String searchURL=GOOGLE_SEARCH_URL+cell.getStringCellValue()+" flag"+"&hl=en&tbm=isch";
System.out.print(searchURL);
Document doc = Jsoup.connect(searchURL).get();
Elements link = doc.select("img.rg_i Q4LuWd");
System.out.println("link2 " +link.attr("src"));
System.out.println("link2 " +link.toString());
}
System.out.println("");
}
}
}
Java code to read all the cells in a sheet including blank cells in excel sheets and insert the same data into postgresql database without editing them.
I have already tried using apache-poi, missingcellpolicy, replacefunction, etc. But, it throws a nullpointerexception.
When I run my code to display the celltype of a cell in excel, it is not displaying any type for blankspaces and skips the cell completely.
Here is the code:
package poiexcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Date;
//import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
#SuppressWarnings("unused")
public class ReadExcel {
public static final String SAMPLE_XLSX_FILE_PATH = "C:\\Raj's Documents\\Documents\\studentdata.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
try {
FileInputStream file = new FileInputStream(new File(SAMPLE_XLSX_FILE_PATH));// Read the spreadsheet that
// needs to be uploaded
XSSFWorkbook myExcelBook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
for (Sheet myExcelsheet : myExcelBook) {
// ArrayList<SheetDetails> details = new ArrayList<SheetDetails>();
// for (Row row : myExcelsheet) {
for (int i = 0; i < myExcelsheet.getPhysicalNumberOfRows(); i++) {
Row row = myExcelsheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
Cell cell = row.getCell(j);
CellType ct = cell.getCellType();
System.out.println(ct);
}
System.out.println();
}
}
myExcelBook.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the output:
NUMERIC
STRING
java.lang.NullPointerException
at poiexcel.ReadExcel.main(ReadExcel.java:52)
Under 'dependencies'in build.gradle (if using Gradle, otherwise find the matching dependency for Maven) file paste the dependency we want:
compile group: 'org.apache.commons', name: 'commons-csv', version: '1.5'
Create the following import:
import org.apache.commons.csv.*;
Parsing an excel csv file is then as easy as:
public Iterable<CSVRecord> parse(String csvPath) throws IOException {
Reader in = new FileReader(csvPath);
return CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
}
EXCEL can be changed to DEFAULT if the csv files are plain text csv files.
We can then use the iterable list to get its values by id, column title or by enum, although these need to be defined. Then persist these values into the relevant database entity via the corresponding repository.
I want to extract the actual series data and values from a chart in xls file using Apache POI. Point Values like the pair (15.44956728, 7) as shown below. I managed to extract the title of the chart but could not do it with the needed data. Here is my code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFChart;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Hello, World");
InputStream inp;
try {
inp = new FileInputStream("USRAK_00017_0.xls");
HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
ExcelExtractor extractor = new ExcelExtractor(wb);
extractor.setFormulasNotResults(true);
extractor.setIncludeSheetNames(true);
String text = extractor.getText();
//System.out.println(text);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFChart[] sheetCharts = HSSFChart.getSheetCharts(sheet);
System.out.println(sheetCharts[0].getSeries()[0].getSeriesTitle());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
A better approach I found is to dump the XLS file to XML content in fods format. Open Office can do this job via the following command:
soffice --headless --convert-to fods USRAK_00017_0.xls
Then you can parse the XML the way you like and parse the part you want to extract from the chart
I am trying to write to Excel using apachee POI. It works when the getrow index is 0 like[getrow(o)]. But changing it other than zero throw nullpointer exception.
package fairfoxchecking;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class writingInExcel {
public static void main(String []args) throws IOException {
File src = new File("D:/Etl_Bug_reporting_Template.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 =wb.getSheetAt(0);
sheet1.getRow(0).createCell(5).setCellValue("cheasdfasdfasck1");
sheet1.getRow(1).createCell(5).setCellValue("cheasdfasdfasck1");
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
wb.close();
}
Before you do create a cell, you have to ensure the row is created.
Try something like,
if(sheet1.getRow(rowIndex) == null)
sheeet1.createRow(rowIndex)
sheet1.getRow(rowIndex).createCell(colIndex).setCellValue(stringVal);
As per this , getRow might return null if it is not defined. So you might have to create one before writing.
sheet1.createRow(index)
Check this lib - seems to be nice.