Importing and exporting of excel file
import java.io.File;
import java.io.FileInputStream; import
java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; 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;
public class ExcelRead {
public static void first() throws FileNotFoundException, IOException {
// import of workbok//
File fs = new File("D:\\Input.xlsx");
FileInputStream fis = new FileInputStream(fs);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
int rownum = sheet.getLastRowNum() + 1;
int colnum = sheet.getRow(0).getLastCellNum();
String[][] data = new String[rownum][colnum];
for (int i = 0; i < rownum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j < colnum; j++) {
XSSFCell Cell = row.getCell(j);
data[i][j] = Cell.toString();
System.out.print(data[i][j] + "\t\t");
}
System.out.println("\t");
System.out.println("\t\t");
}
FileOutputStream fileOut = new FileOutputStream("D:/NewExcelFile.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
}
public static String CellToString() {
XSSFCell cell = null;
int type;
Object result;
type = cell.getCellType();
switch (type) {
case 0:
result = cell.getNumericCellValue();
break;
case 1:
result = cell.getStringCellValue();
break;
default:
throw new RuntimeException("There are no support for this type of cell");
}
return result.toString();
}
}
Try the below code:
FileInputStream file = new FileInputStream(new File("path to xlsx file"));
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator <Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
}
}
Related
I am trying to get input from excel for my testcase . My input contains both string and numeric values. I know how to retrieve value for single datatype using the below code
public Object[][] readnumericvalue() throws IOException {
File src = new File("filepath");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(1);
XSSFRow row = sheet1.getRow(0);
int rowcount = sheet1.getLastRowNum();
int columnCount = row.getLastCellNum();
Object data1[][]=new Double[rowcount+1][columnCount];
columnCount = columnCount-1;
for(int i=0;i<=rowcount;i++) {
for(int j=0;j<=columnCount;j++) {
data1[i[j]= sheet1.getRow(i).getCell(j).getNumericCellValue();
}
}
return data1;
}
I tried to read both the datatypes in single dataprovider but I don't know how to initialize 2D-array for multiple datatypes
File src = new File("");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFRow row = sheet1.getRow(0);
int rowcount = sheet1.getLastRowNum();
int columnCount = row.getLastCellNum();
Object data1[][]=new String[rowcount+1][columnCount];
columnCount = columnCount-1
for(int i=0;i<=rowcount;i++) {
for(int j=0;j<=columnCount;j++) {
Cell cell = row.getCell(j);
switch (cell.getCellTypeEnum()) {
case STRING:
data1[i][j]=sheet1.getRow(i).getCell(j).getStringCellValue();
break;
case NUMERIC:
data1[i][j]=sheet1.getRow(i).getCell(j).getNumericCellValue();
break;
}
}
}
return data1;
If you would like to accommodate both the data types in the same data provider, then you can basically define the array as an Object array.
Here's a sample.
Lets say the excel workbook looks like below
| Name | Age |
|------|-----|
| Jack | 24 |
| Jill | 23 |
| Bob | 30 |
Here's a sample code, that reads this data
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;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
public class SampleTestClass {
#Test(dataProvider = "dp")
public void testMethod(String name, int age) {
System.err.println("Name :" + name + ", Age :" + age);
}
#DataProvider(name = "dp")
public Object[][] readnumericvalue() throws IOException {
File src = new File("src/test/resources/47036541.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
int rowcount = sheet1.getPhysicalNumberOfRows();
int columnCount = sheet1.getRow(0).getLastCellNum();
Object objects[][] = new Object[rowcount-1][columnCount];
int rowCounter = 0;
Iterator<Row> rowIterator = sheet1.iterator();
boolean firstRow = true;
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
if (firstRow) {
firstRow = false;
continue;
}
Iterator<Cell> cellIterator = currentRow.iterator();
int colCounter = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
objects[rowCounter][colCounter] = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
objects[rowCounter][colCounter] = new Double(cell.getNumericCellValue()).intValue();
break;
}
colCounter++;
}
rowCounter++;
}
return objects;
}
}
Here's the output
Name :Jack, Age :24
Name :Jill, Age :23
Name :Bob, Age :30
===============================================
Default Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================
S_No Operators About No.Of-Busses Main-Routes No.Of-Routes Popular-Routes
1 A-G-Holidays *** 10 Delhi - Haridwar Delhi - Haridwar
Delhi - Dehradun
Delhi - Kanpur
Delhi - Lucknow
Delhi - Rishikesh
Rishikesh - Delhi
Kanpur - Lucknow
Haridwar - Delhi
Haridwar - Rishikesh
Haridwar - Dehradun
blank line-----------------------------------------------------------------------
2 A-K-Travels *** 2 0
Mumbai - Indore
Indore - Mumbai
Hi, I Have a Excel Sheet like above. I need to count all popular routes and print that count in No.of-Routes column on corresponding S_No row. Also I have an blank line after every S_No's. And these all popular routes are not placed in one cell(each route is one row).
I tried with below code. I'm not able to move forward,please help me.
public class PrintNoOfRoutes
{
public static void main(String args[]) throws Exception
{
List list=new ArrayList();
FileInputStream file = new FileInputStream(new File("D:/BusOperators/sample.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
Row row = rowIterator.next();
int S_No=(int) row.getCell(0).getNumericCellValue();
System.out.println(S_No);
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:
int S_No=(int) row.getCell(0).getNumericCellValue();
System.out.println(S_No);
break;
case Cell.CELL_TYPE_STRING:
//list.add(cell.getStringCellValue());
if(c==S_No)
{
System.out.println("done");
row.getCell(6);
Row row2 = rowIterator.next();
if(cell.getStringCellValue() != null)
{
count=1;
System.out.println(count);
count++;
}
break;
}
This worked for me. This depends on a blank line to indicate when to stop counting popular routes for a particular S_No. S_No and No.Of-Routes must be numeric fields.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.xssf.usermodel.XSSFWorkbook;
public class PrintNoOfRoutes
{
private static final String INFILE_NAME = "C:\\sample.xlsx";
private static final String OUTFILE_NAME = "C:\\sampleout.xlsx";
public static void main(String[] args) {
try {
FileInputStream excelFile = new FileInputStream(new File(INFILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
boolean firstTime = true;
int numRoutes = 0;
Cell routeCell = null;
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING && currentCell.getColumnIndex() == 6) {
//found a route to count
String val = currentCell.getStringCellValue();
if (!firstTime) //don't count header row
numRoutes++;
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC && currentCell.getColumnIndex() == 0) {
//found an S_No cell with a value
if (!firstTime) {
//set the number of routes for the previous S_No
routeCell.setCellValue(numRoutes);
numRoutes = 0; //reset
} else {
firstTime = false;
}
routeCell = currentRow.getCell(5); //save the No.Of-Routes cell for this S_No
}
}
}
//write last route count
routeCell.setCellValue(numRoutes);
//write out the workbook
File outfile = new File(OUTFILE_NAME);
FileOutputStream fos = new FileOutputStream(outfile);
workbook.write(fos);
workbook.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a large excel file. I want to filter a column "Mainly used for" for values "mainly used for mobile". Then I need to store the corresponding values in the "Number Series" column in a list. I have a code to start with. However I am not able to do the filtering part and storing it to an array list. Could you please help me out here.
I did some digging and have modified the code. However I have not been able to meet my requirement. I have following problems -
*The code only selects two columns and displays their contents. Not able to filter :(
*The excel has column names with spaces. So I am getting the error. As the excel is generated by the user,
we have no control over column names. How to deal with the column name with spaces ??
*Excel has alpha-numeric values, how to deal with them?
Could you please help me out here.
package com.excel;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;*/
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
public class Test {
public static void main(String[] args) throws Exception {
File excel = new File("D:\\FileDownload\\example.xls");
//File excel = new File("D:\\FileDownload\\Sample_Filtered.xls");
FileInputStream fis = new FileInputStream(excel);
//XSSFWorkbook wb = new XSSFWorkbook(fis);
HSSFWorkbook wb = new HSSFWorkbook(fis);
//org.apache.poi.ss.usermodel.Workbook wb = WorkbookFactory.create(fis);
HSSFSheet ws = wb.getSheetAt(0);
// org.apache.poi.ss.usermodel.Sheet ws = wb.getSheetAt(0);
ws.setForceFormulaRecalculation(true);
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
int mainlyUsedForHeaderIndex = -1, mobileSeriesHeaderIndex = -1;
//Read the headers first. Locate the ones you need
HSSFRow rowHeader = ws.getRow(0);
for (int j = 0; j < colNum; j++) {
HSSFCell cell = rowHeader.getCell(j);
String cellValue = cellToString(cell);
if("Mainly used for".equalsIgnoreCase(cellValue)) {
//if("MainlyFor".equalsIgnoreCase(cellValue)) {
mainlyUsedForHeaderIndex = j;
} else if("Number Series".equalsIgnoreCase(cellValue)) {
//else if("MobileSeries".equalsIgnoreCase(cellValue)) {
mobileSeriesHeaderIndex = j;
}
}
if(mainlyUsedForHeaderIndex == -1 || mobileSeriesHeaderIndex == -1) {
throw new Exception("Could not find header indexes\n Mainly used for : " + mainlyUsedForHeaderIndex + " | Number Series: " + mobileSeriesHeaderIndex);
}else{
System.out.println("Indexes are found!!!");
}
//createnew workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("data");
for (int i = 1; i < rowNum; i++) {
HSSFRow row = ws.getRow(i);
//row = sheet.createRow(rowNum++);
String MainlyUsed = cellToString(row.getCell(mainlyUsedForHeaderIndex));
String ForMobile = cellToString(row.getCell(mobileSeriesHeaderIndex));
int cellIndex = 0;
XSSFRow newRow = sheet.createRow(i-1);
newRow.createCell(cellIndex++).setCellValue(MainlyUsed);
newRow.createCell(cellIndex++).setCellValue(ForMobile );
}
FileOutputStream fos = new FileOutputStream(new File("D:\\FileDownload\\test1.xlsx"));
System.out.println("File generated");
workbook.write(fos);
fos.close();
}
public static String cellToString(HSSFCell cell) {
int type;
Object result = null;
type = cell.getCellType();
switch (type) {/*
case HSSFCell.CELL_TYPE_NUMERIC:
result = BigDecimal.valueOf(cell.getNumericCellValue())
.toPlainString();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = "";
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();*/
case HSSFCell.CELL_TYPE_BLANK:
result="";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
//
result = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_ERROR:
//
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
//
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result= cell.getRichStringCellValue();
// result = cell.getStringCellValue();
break;
}
return result.toString();
}
}
I am able to meet my requirement using following entirely different approach.
package com.excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelRead {
public static void main(String[] args) throws IOException{
String fileName = "D:\\FileDownload\\example.xls";
String cellContent = "Mainly used for mobile";
int rownr=0;
int colnr = 0; //column from which you need data to store in array list
InputStream input = new FileInputStream(fileName);
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheetAt(0);
List MobileSeries=new ArrayList();
MobileSeries = findRow(sheet, cellContent);
if(MobileSeries !=null){
for(Iterator iter=MobileSeries.iterator();iter.hasNext();){
System.out.println(iter.next());
}
}
//output(sheet, rownr, colnr);
finish();
}
private static void output(HSSFSheet sheet, int rownr, int colnr) {
/*
* This method displays the total value of the month
*/
HSSFRow row = sheet.getRow(rownr);
HSSFCell cell = row.getCell(colnr);
System.out.println("Your total is: " + cell);
}
private static List findRow(HSSFSheet sheet, String cellContent) {
List MobileSeries=new ArrayList();
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
//System.out.println("Row numbers are"+row.getRowNum());
int rownumber=row.getRowNum();
//return row.getRowNum();
HSSFRow row1 = sheet.getRow(rownumber);
HSSFCell cell1 = row1.getCell(0);
MobileSeries.add(cell1);
}
}
}
}
return MobileSeries;
}
private static void finish() {
System.exit(0);
}
}
I need to read specific column of an excel sheet and then declare the variables in java. The program that I have done reads the entire content of excel sheet. But I need to read a fixed column like C.
This is what I have done:
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class JavaApplication4
{
private String inputFile;
String[][] data = null;
public void setInputFile(String inputFile)
{
this.inputFile = inputFile;
}
public String[][] read() throws IOException
{
File inputWorkbook = new File(inputFile);
Workbook w;
try
{
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
data = new String[sheet.getColumns()][sheet.getRows()];
// Loop over first 10 column and lines
// System.out.println(sheet.getColumns() + " " +sheet.getRows());
for (int j = 0; j <sheet.getColumns(); j++)
{
for (int i = 0; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
data[j][i] = cell.getContents();
// System.out.println(cell.getContents());
}
}
for (int j = 0; j < data.length; j++)
{
for (int i = 0; i <data[j].length; i++)
{
System.out.println(data[j][i]);
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
return data;
}
public static void main(String[] args) throws IOException
{
JavaApplication4 test = new JavaApplication4();
test.setInputFile("C://users/admin/Desktop/Content.xls");
test.read();
}
}
Here is my excel sheet,
From a bowl of chits numbered /#v1#/ to /#v2#/ , a single chit is randomly drawn. Find the probability that the chit drawn is a number that is a multiple of /#v3#/ or /# v4#/?
I need to read this data and by matching the pattern /#v1#1, I need to declare the variables. How can I do this?
What you can do, you should first get all the columns from the sheet by using sheet.getColumns() and store all columns in a list . Then you can match get all values based on columns. or you can get for only column "C".try using below code. let me know if this works.
int masterSheetColumnIndex = sheet.getColumns();
List<String> ExpectedColumns = new ArrayList<String>();
for (int x = 0; x < masterSheetColumnIndex; x++) {
Cell celll = sheet.getCell(x, 0);
String d = celll.getContents();
ExpectedColumns.add(d);
}
LinkedHashMap<String, List<String>> columnDataValues = new LinkedHashMap<String, List<String>>();
List<String> column1 = new ArrayList<String>();
// read values from driver sheet for each column
for (int j = 0; j < masterSheetColumnIndex; j++) {
column1 = new ArrayList<String>();
for (int i = 1; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
column1.add(cell.getContents());
}
columnDataValues.put(ExpectedColumns.get(j), column1);
}
This is the very simple and efficient code and Working as expected
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 TestExcelFile {
public static void main(String[] args) {
String envFilePath = System.getenv("AZURE_FILE_PATH");
// upload list of files/directory to blob storage
File folder = new File(envFilePath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
Workbook workbook;
//int masterSheetColumnIndex = 0;
try {
workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
// Get the first sheet.
Sheet sheet = workbook.getSheetAt(0);
//we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
String columnWanted = "Column_Name";
Integer columnNo = null;
//output all not null values to the list
List<Cell> cells = new ArrayList<Cell>();
// Get the first cell.
Row row = sheet.getRow(0);
//Cell cell = row.getCell(0);
for (Cell cell : row) {
// Column header names.
//System.out.println(cell.toString());
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
if (columnNo != null){
for (Row row1 : sheet) {
Cell c = row1.getCell(columnNo);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
//System.out.println(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + listOfFiles[i].getName());
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
}
}
}
}
Reading Particular column from excel file
File myFile = new File(path);
FileInputStream fis = new FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
//XSSFWorkbook workBook = new XSSFWorkbook();
//Reading sheet at number 0 in spreadsheet(image attached for reference
Sheet sheet = myWorkBook.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
//Reading cell in my case column name is ppm
Cell ppmEx= row.getCell(0);
//Cell cell = cellIterator.next();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
//System.out.println(cell.getNumericCellValue() + " ");
al.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
//System.out.println(cell.getStringCellValue()+" ");
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
//System.out.println(cell.getBooleanCellValue()+" ");
al.add(cell.getBooleanCellValue());
case Cell.CELL_TYPE_BLANK:
//System.out.println("blank");
al.add("blank");
}
}
System.out.println("-");
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xlsxreader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
/**
*
* #author khaled
*/
public class XlsxReader {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
File file = new File("C:\\Users\\khaled\\Desktop\\myXLSX file.xlsx");
Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
Sheet sheet = workbook.getSheetAt(0);
int column_index_1 = 0;
int column_index_2 = 0;
int column_index_3 = 0;
Row row = sheet.getRow(0);
for (Cell cell : row) {
// Column header names.
switch (cell.getStringCellValue()) {
case "MyFirst Column":
column_index_1 = cell.getColumnIndex();
break;
case "3rd Column":
column_index_2 = cell.getColumnIndex();
break;
case "forth Column":
column_index_3 = cell.getColumnIndex();
break;
}
}
for (Row r : sheet) {
if (r.getRowNum()==0) continue;//hearders
Cell c_1 = r.getCell(column_index_1);
Cell c_2 = r.getCell(column_index_2);
Cell c_3 = r.getCell(column_index_3);
if (c_1 != null && c_1.getCellType() != Cell.CELL_TYPE_BLANK
&&c_2 != null && c_2.getCellType() != Cell.CELL_TYPE_BLANK
&&c_3 != null && c_3.getCellType() != Cell.CELL_TYPE_BLANK) {
System.out.print(" "+c_1 + " " + c_2+" "+c_3+"\n");
}
}
}
}
My question is based on this Question. This is my build so far:
package converters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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;
class XlsxtoCSV {
public static void main(String[] args) {
File inputFile = new File(
"C:\\Users\\USR\\Desktop\\testExport.xlsx");
File outputFile = new File("C:\\Users\\USR\\Desktop\\output.csv");
xlsx(inputFile, outputFile);
}
static void xlsx(File inputFile, File outputFile) {
String seperator = ";";
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(
new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
int i = 0; //I need 11 columns which can be empty
while (i < 11) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + seperator);
break;
case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + seperator);
break;
case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + seperator);
break;
case Cell.CELL_TYPE_BLANK:
data.append("" + seperator);
break;
default:
data.append(cell + seperator);
}
}
data.append("\r\n");
i++;
}
fos.write(data.toString().getBytes());
fos.close();
System.out.println(data.toString());
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
but my problem is that it won't work properly if there is an line break in a cell, which is important for me.
I need it to be exactly like when you "save as csv" in Excel.