How to read data from excel sheet using java? - 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();
}

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());

generating report in excel sheet in java

I want to generate Excel Report but I am not able to generate excel report , I don't know what is the problem ?
I need to generate automated report everytime I click on generate report button.
I am using sqlyog,my table name is final and my database name is etc. my database table entries are not static so I need an automated report .
I am using Eclipse IDE
Is it that I need to use any more external api.
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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;
public class ExcelDatabase {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost/etc", "root", "");
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from final");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook.createSheet("engine report");
HSSFRow row = spreadsheet.createRow(1);
HSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("engine_code");
cell = row.createCell(2);
cell.setCellValue("var1");
cell = row.createCell(3);
cell.setCellValue("var2");
cell = row.createCell(4);
cell.setCellValue("var3");
cell = row.createCell(5);
cell.setCellValue("var4");
cell = row.createCell(6);
cell.setCellValue("var5");
cell = row.createCell(7);
cell.setCellValue("User_Name");
cell = row.createCell(8);
cell.setCellValue("time_stamp");
int i = 2;
while (resultSet.next()) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue(resultSet.getInt("ec"));
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("v1"));
cell = row.createCell(3);
cell.setCellValue(resultSet.getString("v2"));
cell = row.createCell(4);
cell.setCellValue(resultSet.getString("v3"));
cell = row.createCell(5);
cell.setCellValue(resultSet.getString("v4"));
cell = row.createCell(6);
cell.setCellValue(resultSet.getString("v5"));
cell = row.createCell(7);
cell.setCellValue(resultSet.getString("user"));
cell = row.createCell(8);
cell.setCellValue(resultSet.getString("time"));
i++;
}
FileOutputStream out = new FileOutputStream(new File("exceldatabase.xls"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xls written successfully");
}
}
I created a same table in database as yours and tried running your code.
i could create Excel file without changing your code.
Just the difference is i used different driver ("oracle.jdbc.driver.OracleDriver"). So first check your database connection. If it is successful then rest of the code should work fine.
Please post the more specific exception if any.
That will help solve the problem.
One more thing you have used indexing from row 1 and cell 1 but POI uses indexing of rows and columns from 0.
Read Excel file and generate report as follows
You can read all rows and columns from excel and display it in your UI.
FileInputStream file = new FileInputStream("exceldatabase.xls");
Workbook wb = new HSSFWorkbook(file);
Sheet sheet = wb.getSheet("engine report");
int lastRowNum = sheet.getLastRowNum();
for(int rowIndex = 0 ; rowIndex < lastRowNum ; rowIndex++){
Row currRow = sheet.getRow(rowIndex);
if(currRow != null) {
List<String> currRowValues = new ArrayList<String>();
for(int cellNo = currRow.getFirstCellNum(); cellNo < currRow.getLastCellNum();cellNo++) {
Cell currCell = currRow.getCell(cellNo);
if(currCell != null) {
int cellType = currCell.getCellType();
switch(cellType) {
case Cell.CELL_TYPE_BLANK :
currRowValues.add("");
break;
case Cell.CELL_TYPE_BOOLEAN :
currRowValues.add(String.valueOf(currCell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC :
currRowValues.add(String.valueOf(currCell.getNumericCellValue()));
break;
case Cell.CELL_TYPE_STRING :
currRowValues.add(currCell.getStringCellValue());
break;
case Cell.CELL_TYPE_ERROR :
currRowValues.add("");
break;
}
} else {
currRowValues.add("");
}
}
// Add your code here
// Add current list to your UI or the way you want to display report
System.out.println( currRowValues);
}
}
For adding Header in Excel file use following code.
You should create a Merged region in sheet.
You can provide range be be merged using CellRangeAddress. Which takes startRow, endRow , startCol ,endCol as values to create cell range address.
After creating merged region you should set the value in left most cell in region i.e. cell at startRow,startCol.
I have used alignment to align content in center.
Save your file and you will get the expected result. :)
HSSFRow createRow = spreadsheet.createRow(0);
CellRangeAddress range = new CellRangeAddress(0, 0, 1, 8);
spreadsheet.addMergedRegion(range);
HSSFCell createCell = createRow.createCell(1);
createCell.setCellValue("My header");//ADD Your Custom Header value Here
CellUtil.setAlignment(createCell, workbook, CellStyle.ALIGN_CENTER);
You can create excel sheet via java code using apache poi library classes like HSSFSheet, HSSFRow.
import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
public class CreateExcel(){
public static void main(String args[]){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet 1");
HSSFRow row = sheet.createRow(rowNumber); // 0,1,2..
HSSFCell cell = row.createCell(columnNumber); // 0,1,2...
cell.setCellValue("Hello Apache POI !");
HSSFFont font = workbook.createFont();
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
workbook.write(baos);
baos.flush();
}
}
Using above program you can create an excel sheet.
It seems you are overwriting the same row and cell objects again and again.
for each new cell you need to create a new object :
//instead of
HSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("engine_code");
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("v1"));
//do
HSSFCell cell1 = row.createCell(1);
cell1.setCellValue("engine_code");
HSSFCell cell2 = row.createCell(2);
cell2.setCellValue(resultSet.getString("v1"));
The same applies to rows objects:
HSSFRow row1 = spreadsheet.createRow(1);
HSSFRow row2 = spreadsheet.createRow(2);

reading xlsx and import it

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 );

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