reading xlsx and import it - java

I am trying to create a class to read a XLSX file when I upload it to a website.
I have the code to upload the file to the server. The file can be uploaded but it can't capture the data from the excel.
May I know how do I solve or modify this code such that the data is being able to be seen on the web?
I know there's some other duplicate questions out there but after trying, those answers can't seem to work for me.
If I remove the line public static void... , then I will get this error: Package should contain a content type part [M1.13]
public HashMap getConstructJXLList_xlsx(UploadedFile File, int Sheetindex) {
String _LOC = "[PageCodeBase: getConstructJXLList_xlsx]";
HashMap _m = new HashMap();
return _m;
}
//InputStream _is = null;
public static void main(String[] args)
{
try {
FileInputStream input = new FileInputStream(new File("C:\\Users\\admin\\Desktop\\Load_AcctCntr_Template.xlsx"));
org.apache.poi.ss.usermodel.Workbook wb = WorkbookFactory.create(input);
org.apache.poi.ss.usermodel.Sheet s = wb.getSheetAt(0);
Iterator<Row> rows = s.rowIterator();
while (rows.hasNext())
{
Row row = rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
XSSFCell cell = (XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue() + "t");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue() + "t");
}
else if(cell.CELL_TYPE_BLANK==cell.getCellType())
System.out.print( "BLANK " );
else
System.out.print("Unknown cell type");
}
input.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
If I just run the main method from above, this is the output:
0000002b SystemOut O [RedirectLogin: requiredRights]1.0en1102.xhtml
0000002b SystemOut O [En1102: doEn1102_command_readfileAction]1.0
0000002b SystemOut O [En1102: onPageLoadBegin]1.0
it seems that the server did not even run through this code above..
I can just download the excel template on the website and it will be saved on my desktop.
The file will contain the title header and I am able to key in whatever data I want in the cells.

To read xlsx files, you should use:
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
XSSFWorkbook wb;
XSSFSheet sheet;
XSSFRow row;
XSSFCell cell;
FileInputStream input = new FileInputStream(new File("C:\\Users\\admin\\Desktop\\Load_AcctCntr_Template.xlsx"));
wb = new XSSFWorkbook(input );

Related

Excel import from csv file to convert

Im having difficulty with using Apache POI API. Im trying to import an excel them only select certain rows and cells to extract from the import. Im currently able to import, but i cant extract certain cell. Here is code:
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.io.IOException;
public class ExcelReader {
public static final String path = "C:/Users/xxxx/Documents/import testing.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
// Create a workbook with data from excel file
Workbook workbook = WorkbookFactory.create(new File(path));
// Save sheets from workbook
Sheet sheet = workbook.getSheetAt(0);
// Make sure the data is saved in string format using a data formatter
DataFormatter dataFormatter = new DataFormatter();
// Iterate through cells and columns, printing their content
System.out.println("\n\nThe content of the excel file: " + path + "\n");
String cellContent;
for (Row row: sheet) {
for(Cell cell: row) {
cellContent = dataFormatter.formatCellValue(cell);
if(cellContent == null || cellContent.trim().isEmpty()){
// Give the empty cells the content "empty", to make it easy to filter out later on
cellContent = "empty";
}
System.out.print(cellContent + "\t");
}
CellReference cellReference = new CellReference("A11");
XSSFRow rowT = sheet.getRow(cellReference.getRow());
if (rowT != null) {
XSSFCell cell = rowT.getCell(cellReference.getCol());
}
System.out.println();
}
// Close the connection to the workbook
workbook.close();
}
}
Changing Workbook to XSSFWorkbook and Sheet to XSSFSheet seems to fix the compilation issue.
XSSFWorkbook workbook = new XSSFWorkbook(new File(path));
and
XSSFSheet sheet = workbook.getSheetAt(0);
try with this for get "A11" cell
XSSFCell cell = sheet.getRow(10).getCell(0); // 10 = id of the 11th row, 0 = id of the 1st (A) column
or
XSSFCell cell = sheet.getRow(10).getCell(CellReference.convertColStringToIndex("A"));
create cell reference for B12
CellReference cr = new CellReference("B12");
row = mySheet.getRow(cr.getRow());
cell = row.getCell(cr.getCol());

How to read data from excel sheet using java?

I am a beginner in Java coding and would like to know how to read the following excel sheet data using Java.
Also, I have tried the below code -
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadingFromExcelSheet {
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
int i,j;
int rowcount =3,cellcount=2;
for ( i=0;i<=rowcount;i++){
for (j=0;j<cellcount;j++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.println(cellval + "\t\t" );
}
}
ip.close();
}
}
And i am getting the below shown output :
Topics
YouTube Links
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
https://youtu.be/Pvcv-V69Vc0
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
Datatypes
Variables
String Concatenation
https://youtu.be/Gx0ubuYwTjg
Global Variables (Static & NonStatic)
Local Variables
Memory Allocation
I am getting the values of the cell but not in their proper order as like the excel sheet. Can anyone please help?
Try this approach
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
//append empty line
System.out.println();
}
ip.close();
}
Does this improve the formatting?
for ( i=0;i<=rowcount;i++)
{
Row row = sheet.getRow(i);
for (j=0;j<cellcount;j++)
{
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.print(cellval + "\t\t" );
}
System.out.println();
}

how to read excel file and insert those data into database using java and poi or any other libraray?

i am using servlet and trying to read the user uploaded excel file and insert into database.
my excel is in this format:
ID IP1 IP2 USER TKTNO(these are headings in excel & database table as well)
under those heading i have data in excel file which i have to read and insert into database.
please desperately need help....thank you
I am using Docx4J for this purpose... good with Docx and xlsx
http://www.docx4java.org/trac/docx4j
this is how you read an excel file using apache POI library , i guess this is good enough for starters , now you can take the cell values stored in some collection objects and store the object to Database according to requirement
package com.Excel;
import java.io.*;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile {
public static void main(String[] args)
{
try {
FileInputStream file = new FileInputStream(new File("C:/Users/hussain.a/Desktop/mar_25/Tradestation_Q4 Dashboard_Week 5_1029-1104.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
while(rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println("numeric===>>>"+cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println("String===>>>"+cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to run this program which read excel using POI

I've try to run this code in eclipse but I've get this: selection does not contain a main type eclipse.
Does anyone know how I will do it? I am newbie in java and I need help!
The program I try to make is to read excel file using POI! :)
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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 sample2 {
private void sample2(test)
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(test);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You cannot run a Java application without a main method.
You need something like the following:
public static void main(String[] args) {
sample2 s = new sample2();
s.sample();
}
Also your code contains a lot of errors. You are:
Missing a main method
Capitalization is wrong
Miss types on the input argument for the sample2 method (String test?)
The code is broken many ways. You duplicated the code to read files twice, for error handling, etc.
Reading a good tutorial on Java would help greatly here. A great tutorial on Java and Excel can be found here, and pay some attention to the main method, that's the entry of your Java application.
Your code will not compile due to the identifier "test" in the sample2 method. Remove it and to run the program :
Just add the following method:
public static void main(String[] args) {
new sample2().sample2();
}

java program to read specific data

I need java code to read data for specific column from excel sheet. – (lo number, line, voucher no, stloc , quantity ,activity.)
These set of values for a particular column will be used for sql query (jdbc-odbc connection done).
The output for the query will be matched with a column in this sheet (this part ll be done later)
Kindly help.
sample excel sheet
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excelfilereading;
/**
*
* #author vkantiya
*/
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class Main {
#SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//
// An excel file name. You can create a file name with a full
// path information.
//
String filename = "FirstExcel.xls";
// Create an ArrayList to store the data read from excel sheet.
//
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
//
// Create a FileInputStream that will be use to read the
// excel file.
//
fis = new FileInputStream(filename);
//
// Create an excel workbook from the file system.
//
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//
// Get the first sheet on the workbook.
//
HSSFSheet sheet = workbook.getSheetAt(0);
//
// When we have a sheet object in hand we can iterator on
// each sheet's rows and on each row's cells. We store the
// data read on an ArrayList so that we can printed the
// content of the excel to the console.
//
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExelData(sheetData);
}
private static void showExelData(List sheetData) {
//
// Iterates the data and print it out to the console.
//
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
HSSFCell cell = (HSSFCell) list.get(j);
System.out.print(
cell.getRichStringCellValue().getString());
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
Have a look at Apache POI - the Java API for Microsoft Documents.
It covers
Excel (SS=HSSF+XSSF)
Word (HWPF+XWPF)
PowerPoint (HSLF+XSLF)
OpenXML4J (OOXML)
OLE2 Filesystem (POIFS)
OLE2 Document Props (HPSF)
Outlook (HSMF)
Visio (HDGF) TNEF (HMEF)
Publisher (HPBF)

Categories

Resources