package com.citi.training.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelTDmp {
private static List<List<String>> readExcel(File file, int sheetIndex) throws IOException {
InputStream stream = new FileInputStream(file);
Workbook workbook = null;
Sheet sheet = null;
Row row = null;
Cell cell = null;
List<List<String>> sheetlist = new ArrayList<List<String>>();
String extension = file.getName().lastIndexOf(".") == -1 ? "" : file.getName().substring(file.getName().lastIndexOf(".") + 1);
if ("xls".equalsIgnoreCase(extension)) {
workbook = new HSSFWorkbook(stream);
} else if ("xlsx".equalsIgnoreCase(extension)) {
workbook = new XSSFWorkbook(stream);
} else {
System.out.println("Bad excel format!");
}
sheet = workbook.getSheetAt(sheetIndex);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
List<String> rowlist = new ArrayList<String>();
row = sheet.getRow(i);
for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
cell = row.getCell(j);
rowlist.add(getCellValue(cell));
}
sheetlist.add(rowlist);
}
stream.close();
return sheetlist;
}
public static String getCellValue(Cell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
public static void writeTxt(List<List<String>> data, String path) throws IOException {
FileWriter fileWriter = new FileWriter(path);
for (List<String> listrow : data) {
StringBuffer tempData = new StringBuffer();
for (int i = 0; i < listrow.size(); i++) {
if (i != listrow.size() - 1) {
tempData.append(listrow.get(i) + "'");
} else {
tempData.append(listrow.get(i));
}
}
tempData.append("\r\n");
fileWriter.write(tempData.toString());
}
fileWriter.flush();
fileWriter.close();
}
public static void main(String[] args) {
String excelPath = "H:\\WORK\\t1.xls";
int sheetIndex = 0;
String resultPath = "H:\\WORK\\t1.txt";
try {
List<List<String>> listsheet = readExcel(new File(excelPath),sheetIndex);
writeTxt(listsheet, resultPath);
} catch (IOException e) {
System.out.println("IOException happened!");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println("other exception happened!");
}
System.out.println("completed....");
}
}