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
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);
}
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 am developing a project which needs a docx file to be converted to pdf. I found same question already posted and used the code which was provided by "Kishan C S". It uses docx4J2.8.1
The code is working fine , pdf is generated but only problem I am facing is that the docx file contains logo.jpg (images header part) which are not converted. Only textual format is converted to pdf.
I am posting the code which I have used. Please let me know what how can I solve the problem
P.S: link I referred Convert docx file into PDF with Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class DocxConverter {
public static void main(String[] args) throws FileNotFoundException, Docx4JException, Exception {
InputStream is = new FileInputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
wordMLPackage.getDocumentModel().getSections().get(i).getPageDimensions();
}
Mapper fontMapper = new IdentityPlusMapper();
PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");//set your desired font
fontMapper.getFontMappings().put("Algerian", font);
wordMLPackage.setFontMapper(fontMapper);
PdfSettings pdfSettings = new PdfSettings();
org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
//To turn off logger
List<Logger> loggers = Collections.<Logger> list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for (Logger logger : loggers) {
logger.setLevel(Level.OFF);
}
OutputStream out = new FileOutputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.pdf"));
conversion.output(out, pdfSettings);
System.out.println("DONE!!");
}
}
I have a code that parses through XML files, edits them and saves them (using dom for this). Now, I have a few files which have the .ftl extension. I have managed to process the ftl file with given answers (using freemarker template configuration) , However, I am unable to save the edited xml back as an FTL.
All of this is in Java. Any suggestions on how I can achieve the saving aspect of the problem?
Again, I want to process, edit and then save an FTL file in Java.
I am appending the code that I have for processing the ftl file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FTLReader {
public static void main(String[] args) {
//Freemarker configuration object
Configuration cfg = new Configuration();
try {
//Load template from source folder
Template template = cfg.getTemplate(filename);
// Build the data-model
Map<String,Object> data = new HashMap<String,Object>();
JsonParser parser = new JsonParser();
//write code to get answers
Object obj = parser.parse(new FileReader("src/answers.txt"));
JsonObject jsonObject = (JsonObject) obj;
data.put("element1", jsonObject.get("element1"));
// Console output
Writer out = new OutputStreamWriter(System.out);
template.process(data, out);
out.flush();
/*write code to edit and save the ftl file
*
*
*
*
* */
// File output (the processed FTL file)
Writer file = new FileWriter (new File("C:\\FTL_helloworld.txt"));
template.process(data, file);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
After reading your question and comments few times, I am probably finally getting to grasp what you are aiming to. So, you have to "patch" the file behind the filename variable from the start of your code (Template template = cfg.getTemplate(filename);). FTL file is basically a text file, so you can process it line by line. Then you must re-initialize your template with the new file content, i.e. do template = cfg.getTemplate(filename); again.
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();
}
}}