Create an XLSX file using POI - java

I have two programs in Java: one to create and write data to an XLSX file and the other to read data from the same file.
In my first program, I used the statements below to write data to the XLSX file.
FileOutputStream prelimOut = new FileOutputStream(new File("D:\\News\\Prelim.xlsx"));
XSSFWorkbook out = new XSSFWorkbook();
XSSFSheet spreadSheet = out.createSheet("ResultSheet");
and on my drive, I've the file created as expected.
When I'm trying to read the same file from a different program with this code
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 GetCellCount {
public static void main(String[] args) throws IOException {
FileInputStream input_document = new FileInputStream(new File("D:\\News\\Prelim.xlsx"));
XSSFWorkbook my_xlsx_workbook = new XSSFWorkbook(input_document);
XSSFSheet my_worksheet = my_xlsx_workbook.getSheetAt(0);
Iterator<Row> rowIterator = my_worksheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
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("");
}
my_xlsx_workbook.close();
input_document.close();
}
}
it throws the below error
Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:258)
at GetCellCount.main(GetCellCount.java:14)
Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:203)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:673)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:274)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
... 2 more
When changing the path and accessing another XLSX file (created directly in Excel), the data appears correctly.
Also, when I checked the properties of both these Excel files by right-clicking on them, I see the "Type of File" as MS Office Excel OpenXML (.xlsx), which is the same for both files.

The following code demonstrates creating a new XLSX file with data, writing it to disk, and reading the data back from the file.
The example uses a simple Person class containing a String, a LocalDate, and an Int to produce test data.
This is the created XLSX file viewed with LibreOffice after we've written that test data to it:
After writing the file, we read its contents back in and create Person objects:
Could not parse row 0 to person
Person from file: Khaled, born 1988-03-26, pets: 1
Person from file: Hans, born 1998-09-20, pets: 2
Person from file: Alena, born 1977-01-12, pets: 0
The warning in the first line occurs since we can't convert the header row
Name Date of Birth Nr of Pets
to a Person object.
Here's the code taken from the repository containing the complete project:
/**
* Writes person data to an XLSX file and reads it back from the file.
*/
public class ReadWriteTests {
public static void main(String... args) {
var people = List.of(
new Person("Khaled", LocalDate.of(1988, 3, 26), 1),
new Person("Hans", LocalDate.of(1998, 9, 20), 2),
new Person("Alena", LocalDate.of(1977, 1, 12), 0)
);
String xlsxFileName = System.getenv("HOME") + "/people.xlsx";
writeToXlsxFile(people, xlsxFileName);
List<Person> peopleFromFile = readFromXlsxFile(xlsxFileName);
peopleFromFile.forEach(person ->
System.out.println("Person from file: " + person));
}
private static List<Person> readFromXlsxFile(String xlsxFileName) {
return getRows(new File(xlsxFileName)).stream()
.map(row -> rowToPerson(row))
// Remove empty Optionals
.flatMap(Optional::stream)
.collect(Collectors.toList());
}
private static Optional<Person> rowToPerson(Row row) {
Optional<Person> personMaybe;
try {
String name = row.getCell(0).getStringCellValue();
Date date = row.getCell(1).getDateCellValue();
// Convert from Date to LocalDate
LocalDate dateOfBirth = LocalDate.ofInstant(
date.toInstant(), ZoneId.systemDefault());
int nrOfPets = (int) row.getCell(2).getNumericCellValue();
personMaybe = Optional.of(new Person(name, dateOfBirth, nrOfPets));
} catch (IllegalStateException ex) {
System.err.println("Could not parse row " + row.getRowNum()
+ " to person");
personMaybe = Optional.empty();
}
return personMaybe;
}
private static List<Row> getRows(File xlsx) {
var rows = new ArrayList<Row>();
try (var workbook = new XSSFWorkbook(xlsx)) {
// Get each row from each sheet
workbook.forEach(sheet -> sheet.forEach(rows::add));
// If Apache POI tries to open a non-existent file it will throw
// an InvalidOperationException, if it's an unrecognized format
// it will throw a NotOfficeXmlFileException.
// We catch them all to be safe.
} catch (Exception e) {
System.err.println("Could not get rows from "
+ xlsx.getAbsolutePath());
e.printStackTrace();
}
return rows;
}
private static void writeToXlsxFile(List<Person> people, String fileName) {
try (var fileStream = new FileOutputStream(fileName);
var workbook = new XSSFWorkbook()
) {
var sheet = workbook.createSheet("Test People Sheet");
// Create a header row describing what the columns mean
CellStyle boldStyle = workbook.createCellStyle();
var font = workbook.createFont();
font.setBold(true);
boldStyle.setFont(font);
var headerRow = sheet.createRow(0);
addStringCells(headerRow,
List.of("Name", "Date of Birth", "Nr of Pets"),
boldStyle);
// Define how a cell containing a date is displayed
CellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(workbook.getCreationHelper()
.createDataFormat()
.getFormat("yyyy/m/d"));
// Add the person data as rows
for (int i = 0; i < people.size(); i++) {
// Add one due to the header row
var row = sheet.createRow(i + 1);
var person = people.get(i);
addCells(person, row, dateCellStyle);
}
workbook.write(fileStream);
} catch (IOException e) {
System.err.println("Could not create XLSX file at " + fileName);
e.printStackTrace();
}
}
private static void addCells(Person person, Row row,
CellStyle dateCellStyle) {
var classCell = row.createCell(0, CellType.STRING);
classCell.setCellValue(person.getName());
var dateOfBirthCell = row.createCell(1, CellType.NUMERIC);
// Convert LocalDate to a legacy Date object
Date dateOfBirth = Date.from(person.getDateOfBirth()
.atStartOfDay(ZoneId.systemDefault()).toInstant());
dateOfBirthCell.setCellValue(dateOfBirth);
dateOfBirthCell.setCellStyle(dateCellStyle);
var petCell = row.createCell(2, CellType.NUMERIC);
petCell.setCellValue(person.getNrOfPets());
}
// Adds strings as styled cells to a row
private static void addStringCells(Row row, List<String> strings,
CellStyle style) {
for (int i = 0; i < strings.size(); i++) {
var cell = row.createCell(i, CellType.STRING);
cell.setCellValue(strings.get(i));
cell.setCellStyle(style);
}
}
static class Person {
private final String name;
private final LocalDate dateOfBirth;
private final int nrOfPets;
Person(String name, LocalDate dateOfBirth, int nrOfPets) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.nrOfPets = nrOfPets;
}
String getName() {
return name;
}
LocalDate getDateOfBirth() {
return dateOfBirth;
}
int getNrOfPets() {
return nrOfPets;
}
#Override
public String toString() {
return name + ", born " + dateOfBirth + ", pets: " + nrOfPets;
}
}
}
Here's more on creating spreadsheets with Apache POI.

Related

How to write data into multiple sheets in same excel [duplicate]

This question already has an answer here:
Creating multiple sheets using Apache poi and servlets
(1 answer)
Closed 1 year ago.
I am trying to write the data into same excel file in different sheets, below is the code I tried here only one sheet is creating and data is updating in that sheet, new sheet name is overriding on old sheet. Here I am calling call method two times with 2 different sheet name, when we call from 1st time data need to update in sheet1 and 2nd time call data need to update in sheet2 but in this code only sheet2 is creating and data updating in that.
public static void call(Map<String, String[]> dataListLMS_IPS, String sheet)
{
try {
String filePath = "C:\\Users\\PATIV25\\Downloads\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.close();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheet);
XSSFRow row;
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
Cell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
// .xlsx is the format for Excel Sheets...
// writing the workbook into the file...
FileOutputStream out = new FileOutputStream(theDir);
workbook.write(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
call(data, "sheet1");
call(data, "sheet2");
}
The existing logic is incorrect. You need to separate the creation of file and sheets into different sections if you want to call the call method twice. Try this:
public static void call(Map<String, String[]> dataListLMS_IPS, FileOutputStream fileOut) throws IOException
{
XSSFWorkbook workbook = new XSSFWorkbook();
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
XSSFSheet spreadsheet = workbook.createSheet(key);
XSSFRow row;
row = spreadsheet.createRow(0);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
XSSFCell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
workbook.write(fileOut);
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
FileOutputStream fileOut = null;
try {
String filePath = "d:\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
fileOut = new FileOutputStream(filename);
call(data, fileOut);
call(data, fileOut);
}
catch (Exception e)
{
e.printStackTrace();
} finally {
if (fileOut != null)
fileOut.close();
}
}
It will create 2 sheets in the same Excel file.

How to extract data from Excel sheet using Apache POI in java(lookup framing)

public class Array_Learn {
public static void main(String[] args) {
try {
FileInputStream ExcelFile = new FileInputStream(new File("C:\\Users\\Anbu.B\\Desktop\\POI-Test\\mediTask.xlsx"));
XSSFWorkbook book1 = new XSSFWorkbook(ExcelFile);
XSSFSheet sheet = book1.getSheetAt(0);
Iterator<Row> rowiter = sheet.iterator();
while (rowiter.hasNext()) {
XSSFRow row = (XSSFRow) rowiter.next();
if (row.getRowNum() == 2) {
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
XSSFCell cell = (XSSFCell) cellIterator.next();
if (cell.getStringCellValue().contains("|")) {
String split[] = cell.getStringCellValue().split("\\|");
}
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I need this output:
chest&&pain=J90
lung&&pneumonia=J54.9
lungs&&pneumonia=J54.9
bronchi&&pneumonia=J54.9
bronchus&&pneumonia=J54.9
colon&&ascending&tumor=D12.5
colon&&ascending&carcinoma=D12.5
colon&&ascending&cancer=D12.5
colon&&ascending&&tumor&&resection=D12.6
colon&&descending&&tumor&&resection=D12.6
colon&&ascending&&carcinoma&&resection=D12.6
colon&&descending&&carcinoma&&resection=D12.6
colon&&ascending&&cancer&&resection=D12.6
colon&&descending&&cancer&&resection=D12.6
The above code is doing read row and iterate each cell and check cell contains | symbol condition is true the split statement is working but, I need the above exact output. What I did in the above code:
Read the excel file.
Read sheet from the excel file.
then create row iterator.
create cell iterator.
check cell contains | symbol then split that cell strings and store into the string array.
You almost finished your task. The key here to use one of the algorithms to generate combinations. You could find a general description of such algorithms there, or more close examples with strings on java there.
Full code example (recursive algorithm):
The ParsedRow class for calculating of different combinations:
class ParsedRow {
private final List<List<String>> combinations;
private final String suffix;
public ParsedRow(List<List<String>> combinations, String suffix) {
this.combinations = combinations;
this.suffix = suffix;
}
public List<String> combine() {
List<String> res = new ArrayList<>();
combine(res, 0, "");
return res;
}
public void combine(List<String> res, int depth, String current) {
if (combinations.size() == depth) {
res.add(current + "=" + suffix);
return;
}
String delimiter = current.isEmpty() ? "" : "&&";
for (int i = 0; i < combinations.get(depth).size(); i++) {
combine(res, depth + 1, current + delimiter + combinations.get(depth).get(i));
}
}
}
The Main class for reading the xlsx file and printing results
public class Main {
public static void main(String[] args) throws IOException {
try (final FileInputStream file = new FileInputStream("diseases.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file)) {
List<String> finalResult = new ArrayList<>();
for (Row row : workbook.getSheetAt(0)) {
List<List<String>> combinations = new ArrayList<>();
String suffix = "";
for (Cell cell : row) {
if (cell.getColumnIndex() != 4) {
final List<String> strings = Arrays.asList(cell.getStringCellValue().split("\\|"));
combinations.add(strings);
} else {
suffix = cell.getStringCellValue();
}
}
ParsedRow parsedRow = new ParsedRow(combinations, suffix);
finalResult.addAll(parsedRow.combine());
}
for (String line : finalResult) {
System.out.println(line);
}
}
}
}

converting excel data to JSON format

I am trying to convert excel data into JSON format. but the problem is I have excel sheets which are linked to multiple excel sheet. like example root.xlsx which contains
id, name, phone,department,category,age fields
and where department field refers to department.xlsx which contains
dname, did, dtype
and category fields refers to category.xlsx which contains
catid,catname,cattype,
how to convert it to JSON if the data format is like this?
Jars Required
commons-beanutils-1.8.3.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
json-lib-2.4-jdk15.jar
poi
Sample code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.json.Json;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import net.sf.json.JSONObject;
public class ReadExcelDataWithDynamicColumn {
public static void main(String[] args)
{
// You can specify your excel file path.
String excelFilePath = "/Users/zhaosong/Documents/WorkSpace/EmployeeInfo.xls";
// This method will read each sheet data from above excel file and create a JSON and a text file to save the sheet data.
creteJSONAndTextFileFromExcel(excelFilePath);
}
/* Read data from an excel file and output each sheet data to a json file and a text file.
* filePath : The excel file store path.
* */
private static void creteJSONAndTextFileFromExcel(String filePath)
{
try{
/* First need to open the file. */
FileInputStream fInputStream = new FileInputStream(filePath.trim());
/* Create the workbook object to access excel file. */
//Workbook excelWookBook = new XSSFWorkbook(fInputStream)
/* Because this example use .xls excel file format, so it should use HSSFWorkbook class. For .xlsx format excel file use XSSFWorkbook class.*/;
Workbook excelWorkBook = new HSSFWorkbook(fInputStream);
// Get all excel sheet count.
int totalSheetNumber = excelWorkBook.getNumberOfSheets();
// Loop in all excel sheet.
for(int i=0;i<totalSheetNumber;i++)
{
// Get current sheet.
Sheet sheet = excelWorkBook.getSheetAt(i);
// Get sheet name.
String sheetName = sheet.getSheetName();
if(sheetName != null && sheetName.length() > 0)
{
// Get current sheet data in a list table.
List<List<String>> sheetDataTable = getSheetDataList(sheet);
// Generate JSON format of above sheet data and write to a JSON file.
String jsonString = getJSONStringFromList(sheetDataTable);
String jsonFileName = sheet.getSheetName() + ".json";
writeStringToFile(jsonString, jsonFileName);
// Generate text table format of above sheet data and write to a text file.
String textTableString = getTextTableStringFromList(sheetDataTable);
String textTableFileName = sheet.getSheetName() + ".txt";
writeStringToFile(textTableString, textTableFileName);
}
}
// Close excel work book object.
excelWorkBook.close();
}catch(Exception ex){
System.err.println(ex.getMessage());
}
}
/* Return sheet data in a two dimensional list.
* Each element in the outer list is represent a row,
* each element in the inner list represent a column.
* The first row is the column name row.*/
private static List<List<String>> getSheetDataList(Sheet sheet)
{
List<List<String>> ret = new ArrayList<List<String>>();
// Get the first and last sheet row number.
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
if(lastRowNum > 0)
{
// Loop in sheet rows.
for(int i=firstRowNum; i<lastRowNum + 1; i++)
{
// Get current row object.
Row row = sheet.getRow(i);
// Get first and last cell number.
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getLastCellNum();
// Create a String list to save column data in a row.
List<String> rowDataList = new ArrayList<String>();
// Loop in the row cells.
for(int j = firstCellNum; j < lastCellNum; j++)
{
// Get current cell.
Cell cell = row.getCell(j);
// Get cell type.
int cellType = cell.getCellType();
if(cellType == CellType.NUMERIC.getCode())
{
double numberValue = cell.getNumericCellValue();
// BigDecimal is used to avoid double value is counted use Scientific counting method.
// For example the original double variable value is 12345678, but jdk translated the value to 1.2345678E7.
String stringCellValue = BigDecimal.valueOf(numberValue).toPlainString();
rowDataList.add(stringCellValue);
}else if(cellType == CellType.STRING.getCode())
{
String cellValue = cell.getStringCellValue();
rowDataList.add(cellValue);
}else if(cellType == CellType.BOOLEAN.getCode())
{
boolean numberValue = cell.getBooleanCellValue();
String stringCellValue = String.valueOf(numberValue);
rowDataList.add(stringCellValue);
}else if(cellType == CellType.BLANK.getCode())
{
rowDataList.add("");
}
}
// Add current row data list in the return list.
ret.add(rowDataList);
}
}
return ret;
}
/* Return a JSON string from the string list. */
private static String getJSONStringFromList(List<List<String>> dataTable)
{
String ret = "";
if(dataTable != null)
{
int rowCount = dataTable.size();
if(rowCount > 1)
{
// Create a JSONObject to store table data.
JSONObject tableJsonObject = new JSONObject();
// The first row is the header row, store each column name.
List<String> headerRow = dataTable.get(0);
int columnCount = headerRow.size();
// Loop in the row data list.
for(int i=1; i<rowCount; i++)
{
// Get current row data.
List<String> dataRow = dataTable.get(i);
// Create a JSONObject object to store row data.
JSONObject rowJsonObject = new JSONObject();
for(int j=0;j<columnCount;j++)
{
String columnName = headerRow.get(j);
String columnValue = dataRow.get(j);
rowJsonObject.put(columnName, columnValue);
}
tableJsonObject.put("Row " + i, rowJsonObject);
}
// Return string format data of JSONObject object.
ret = tableJsonObject.toString();
}
}
return ret;
}
/* Return a text table string from the string list. */
private static String getTextTableStringFromList(List<List<String>> dataTable)
{
StringBuffer strBuf = new StringBuffer();
if(dataTable != null)
{
// Get all row count.
int rowCount = dataTable.size();
// Loop in the all rows.
for(int i=0;i<rowCount;i++)
{
// Get each row.
List<String> row = dataTable.get(i);
// Get one row column count.
int columnCount = row.size();
// Loop in the row columns.
for(int j=0;j<columnCount;j++)
{
// Get column value.
String column = row.get(j);
// Append column value and a white space to separate value.
strBuf.append(column);
strBuf.append(" ");
}
// Add a return character at the end of the row.
strBuf.append("\r\n");
}
}
return strBuf.toString();
}
/* Write string data to a file.*/
private static void writeStringToFile(String data, String fileName)
{
try
{
// Get current executing class working directory.
String currentWorkingFolder = System.getProperty("user.dir");
// Get file path separator.
String filePathSeperator = System.getProperty("file.separator");
// Get the output file absolute path.
String filePath = currentWorkingFolder + filePathSeperator + fileName;
// Create File, FileWriter and BufferedWriter object.
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
BufferedWriter buffWriter = new BufferedWriter(fw);
// Write string data to the output file, flush and close the buffered writer object.
buffWriter.write(data);
buffWriter.flush();
buffWriter.close();
System.out.println(filePath + " has been created.");
}catch(IOException ex)
{
System.err.println(ex.getMessage());
}
}
}
for more details visit https://www.dev2qa.com/convert-excel-to-json-in-java-example/

Retrieving selective sheet data from "large Excel 2003" file using java [duplicate]

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to use any external lib or does Java have built-in support for it?
I want to do the following:
for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]
for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
First add all these jar files in your project class path:
poi-scratchpad-3.7-20101029
poi-3.2-FINAL-20081019
poi-3.7-20101029
poi-examples-3.7-20101029
poi-ooxml-3.7-20101029
poi-ooxml-schemas-3.7-20101029
xmlbeans-2.3.0
dom4j-1.6.1
Code for writing in a excel file:
public static void main(String[] args) {
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
data.put("2", new Object[]{1, "Amit", "Shukla"});
data.put("3", new Object[]{2, "Lokesh", "Gupta"});
data.put("4", new Object[]{3, "John", "Adwards"});
data.put("5", new Object[]{4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excelsheet
Row row = sheet.createRow(rownum++);
//get object array of prerticuler key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
Code for reading from excel file
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.
There is a new easy and very cool tool (10x to Kfir): xcelite
Write:
public class User {
#Column (name="Firstname")
private String firstName;
#Column (name="Lastname")
private String lastName;
#Column
private long id;
#Column
private Date birthDate;
}
Xcelite xcelite = new Xcelite();
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users);
xcelite.write(new File("users_doc.xlsx"));
Read:
Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
XceliteSheet sheet = xcelite.getSheet("users");
SheetReader<User> reader = sheet.getBeanReader(User.class);
Collection<User> users = reader.read();
For reading a xlsx file we can use Apache POI libs
Try this:
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
.csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.
A simple CSV file should suffice
String path="C:\\Book2.xlsx";
try {
File f = new File( path );
Workbook wb = WorkbookFactory.create(f);
Sheet mySheet = wb.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
{
for ( Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ; )
{
System.out.println ( ( (Cell)cellIterator.next() ).toString() );
}
System.out.println( " **************************************************************** ");
}
} catch ( Exception e )
{
System.out.println( "exception" );
e.printStackTrace();
}
and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project
For reading data from .xlsx workbooks we need to use XSSFworkbook classes.
XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);
XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.
We need to use Apache-poi 3.9 # http://poi.apache.org/
For detailed info with example visit
: http://java-recent.blogspot.in
Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
using spring apache poi repo
if (fileName.endsWith(".xls")) {
File myFile = new File("file location" + fileName);
FileInputStream fis = new FileInputStream(myFile);
org.apache.poi.ss.usermodel.Workbook workbook = null;
try {
workbook = WorkbookFactory.create(fis);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.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();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
}
I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
}
cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell(c);
if(cell != null) {
System.out.print(cell+"\n");//Your Code here
}
}
}
}} catch(Exception ioe) {
ioe.printStackTrace();}
If column number are varing you can use this
package com.org.tests;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelSimpleTest
{
String path;
public FileInputStream fis = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public ExcelSimpleTest() throws IOException
{
path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
}
public void ExelWorks()
{
int index = workbook.getSheetIndex("Sheet1");
sheet = workbook.getSheetAt(index);
int rownumber=sheet.getLastRowNum()+1;
for (int i=1; i<rownumber; i++ )
{
row = sheet.getRow(i);
int colnumber = row.getLastCellNum();
for (int j=0; j<colnumber; j++ )
{
cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
}
public static void main(String[] args) throws IOException
{
ExcelSimpleTest excelwork = new ExcelSimpleTest();
excelwork.ExelWorks();
}
}
The corresponding mavendependency can be found here
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
Import data
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Export data
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
You need Apache POI library and this code below should help you
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
//*************************************************************
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//*************************************************************
public class AdvUse {
private static Workbook wb ;
private static Sheet sh ;
private static FileInputStream fis ;
private static FileOutputStream fos ;
private static Row row ;
private static Cell cell ;
private static String ExcelPath ;
//*************************************************************
public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
try {
File f= new File(ExcelPath);
if(!f.exists()){
f.createNewFile();
System.out.println("File not Found so created");
}
fis = new FileInputStream("./testData.xlsx");
wb = WorkbookFactory.create(fis);
sh = wb.getSheet("SheetName");
if(sh == null){
sh = wb.getSheet(SheetName);
}
}catch(Exception e)
{System.out.println(e.getMessage());
}
}
//*************************************************************
public static void setCellData(String text , int rowno , int colno){
try{
row = sh.getRow(rowno);
if(row == null){
row = sh.createRow(rowno);
}
cell = row.getCell(colno);
if(cell!=null){
cell.setCellValue(text);
}
else{
cell = row.createCell(colno);
cell.setCellValue(text);
}
fos = new FileOutputStream(ExcelPath);
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
//*************************************************************
public static String getCellData(int rowno , int colno){
try{
cell = sh.getRow(rowno).getCell(colno);
String CellData = null ;
switch(cell.getCellType()){
case STRING :
CellData = cell.getStringCellValue();
break ;
case NUMERIC :
CellData = Double.toString(cell.getNumericCellValue());
if(CellData.contains(".o")){
CellData = CellData.substring(0,CellData.length()-2);
}
break ;
case BLANK :
CellData = ""; break ;
}
return CellData;
}catch(Exception e){return ""; }
}
//*************************************************************
public static int getLastRow(){
return sh.getLastRowNum();
}
You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.
Open the file to Input stream
Open the same file to an Output Stream
Read and do the processing
Write contents to output stream.
Close the read/input stream, close file
Close output stream, close file.
Apache POI - read/write same excel example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
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 XLSXReaderWriter {
public static void main(String[] args) {
try {
File excel = new File("D://raju.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column of Excel file
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");
}
// writing data into XLSX file
Map<String, Object[]> newData = new HashMap<String, Object[]>();
newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
"SGD" });
newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
"USD" });
newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
"INR" });
Set<String> newRows = newData.keySet();
int rownum = sheet.getLastRowNum();
for (String key : newRows) {
Row row = sheet.createRow(rownum++);
Object[] objArr = newData.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
// open an OutputStream to save written data into Excel file
FileOutputStream os = new FileOutputStream(excel);
book.write(os);
System.out.println("Writing on Excel file Finished ...");
// Close workbook, OutputStream and Excel file to prevent leak
os.close();
book.close();
fis.close();
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Please use Apache POI libs and try this.
try
{
FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));
//Create Workbook instance holding reference to .xlsx file
Workbook workbook = new HSSFWorkbook(x);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
Row row = (Row) iterator.next();
for (Iterator<Cell> iterator2 = row.iterator(); iterator2
.hasNext();) {
Cell cell = (Cell) iterator2.next();
System.out.println(cell.getStringCellValue());
}
}
x.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
When using the apache poi 4.1.2. The celltype changes a bit. Below is an example
try {
File excel = new File("/home/name/Downloads/bb.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.
e.g
Sample code:
1.
//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cells iterator
Iterator itrat = ws.getCells().iterator();
//Print cells name in iterator
while(itrat.hasNext())
{
Cell cell = (Cell)itrat.next();
System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
This will write a JTable to a tab separated file that can be easily imported into Excel. This works.
If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.
This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
public class excel {
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
// Create some data
String dataValues[][] =
{
{ "12", "234", "67" },
{ "-123", "43", "853" },
{ "93", "89.2", "109" },
{ "279", "9033", "3092" }
};
JTable table;
excel() {
table = new JTable( dataValues, columnNames );
}
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static void main(String[] o) {
excel cv = new excel();
cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
}
}

How to read and write excel file

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to use any external lib or does Java have built-in support for it?
I want to do the following:
for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]
for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
First add all these jar files in your project class path:
poi-scratchpad-3.7-20101029
poi-3.2-FINAL-20081019
poi-3.7-20101029
poi-examples-3.7-20101029
poi-ooxml-3.7-20101029
poi-ooxml-schemas-3.7-20101029
xmlbeans-2.3.0
dom4j-1.6.1
Code for writing in a excel file:
public static void main(String[] args) {
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
data.put("2", new Object[]{1, "Amit", "Shukla"});
data.put("3", new Object[]{2, "Lokesh", "Gupta"});
data.put("4", new Object[]{3, "John", "Adwards"});
data.put("5", new Object[]{4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excelsheet
Row row = sheet.createRow(rownum++);
//get object array of prerticuler key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
Code for reading from excel file
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.
There is a new easy and very cool tool (10x to Kfir): xcelite
Write:
public class User {
#Column (name="Firstname")
private String firstName;
#Column (name="Lastname")
private String lastName;
#Column
private long id;
#Column
private Date birthDate;
}
Xcelite xcelite = new Xcelite();
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users);
xcelite.write(new File("users_doc.xlsx"));
Read:
Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
XceliteSheet sheet = xcelite.getSheet("users");
SheetReader<User> reader = sheet.getBeanReader(User.class);
Collection<User> users = reader.read();
For reading a xlsx file we can use Apache POI libs
Try this:
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
.csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.
A simple CSV file should suffice
String path="C:\\Book2.xlsx";
try {
File f = new File( path );
Workbook wb = WorkbookFactory.create(f);
Sheet mySheet = wb.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
{
for ( Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ; )
{
System.out.println ( ( (Cell)cellIterator.next() ).toString() );
}
System.out.println( " **************************************************************** ");
}
} catch ( Exception e )
{
System.out.println( "exception" );
e.printStackTrace();
}
and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project
For reading data from .xlsx workbooks we need to use XSSFworkbook classes.
XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);
XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.
We need to use Apache-poi 3.9 # http://poi.apache.org/
For detailed info with example visit
: http://java-recent.blogspot.in
Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
using spring apache poi repo
if (fileName.endsWith(".xls")) {
File myFile = new File("file location" + fileName);
FileInputStream fis = new FileInputStream(myFile);
org.apache.poi.ss.usermodel.Workbook workbook = null;
try {
workbook = WorkbookFactory.create(fis);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.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();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
}
I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
}
cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell(c);
if(cell != null) {
System.out.print(cell+"\n");//Your Code here
}
}
}
}} catch(Exception ioe) {
ioe.printStackTrace();}
If column number are varing you can use this
package com.org.tests;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelSimpleTest
{
String path;
public FileInputStream fis = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public ExcelSimpleTest() throws IOException
{
path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
}
public void ExelWorks()
{
int index = workbook.getSheetIndex("Sheet1");
sheet = workbook.getSheetAt(index);
int rownumber=sheet.getLastRowNum()+1;
for (int i=1; i<rownumber; i++ )
{
row = sheet.getRow(i);
int colnumber = row.getLastCellNum();
for (int j=0; j<colnumber; j++ )
{
cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
}
public static void main(String[] args) throws IOException
{
ExcelSimpleTest excelwork = new ExcelSimpleTest();
excelwork.ExelWorks();
}
}
The corresponding mavendependency can be found here
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
Import data
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Export data
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
You need Apache POI library and this code below should help you
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
//*************************************************************
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//*************************************************************
public class AdvUse {
private static Workbook wb ;
private static Sheet sh ;
private static FileInputStream fis ;
private static FileOutputStream fos ;
private static Row row ;
private static Cell cell ;
private static String ExcelPath ;
//*************************************************************
public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
try {
File f= new File(ExcelPath);
if(!f.exists()){
f.createNewFile();
System.out.println("File not Found so created");
}
fis = new FileInputStream("./testData.xlsx");
wb = WorkbookFactory.create(fis);
sh = wb.getSheet("SheetName");
if(sh == null){
sh = wb.getSheet(SheetName);
}
}catch(Exception e)
{System.out.println(e.getMessage());
}
}
//*************************************************************
public static void setCellData(String text , int rowno , int colno){
try{
row = sh.getRow(rowno);
if(row == null){
row = sh.createRow(rowno);
}
cell = row.getCell(colno);
if(cell!=null){
cell.setCellValue(text);
}
else{
cell = row.createCell(colno);
cell.setCellValue(text);
}
fos = new FileOutputStream(ExcelPath);
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
//*************************************************************
public static String getCellData(int rowno , int colno){
try{
cell = sh.getRow(rowno).getCell(colno);
String CellData = null ;
switch(cell.getCellType()){
case STRING :
CellData = cell.getStringCellValue();
break ;
case NUMERIC :
CellData = Double.toString(cell.getNumericCellValue());
if(CellData.contains(".o")){
CellData = CellData.substring(0,CellData.length()-2);
}
break ;
case BLANK :
CellData = ""; break ;
}
return CellData;
}catch(Exception e){return ""; }
}
//*************************************************************
public static int getLastRow(){
return sh.getLastRowNum();
}
You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.
Open the file to Input stream
Open the same file to an Output Stream
Read and do the processing
Write contents to output stream.
Close the read/input stream, close file
Close output stream, close file.
Apache POI - read/write same excel example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
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 XLSXReaderWriter {
public static void main(String[] args) {
try {
File excel = new File("D://raju.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column of Excel file
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");
}
// writing data into XLSX file
Map<String, Object[]> newData = new HashMap<String, Object[]>();
newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
"SGD" });
newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
"USD" });
newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
"INR" });
Set<String> newRows = newData.keySet();
int rownum = sheet.getLastRowNum();
for (String key : newRows) {
Row row = sheet.createRow(rownum++);
Object[] objArr = newData.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
// open an OutputStream to save written data into Excel file
FileOutputStream os = new FileOutputStream(excel);
book.write(os);
System.out.println("Writing on Excel file Finished ...");
// Close workbook, OutputStream and Excel file to prevent leak
os.close();
book.close();
fis.close();
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Please use Apache POI libs and try this.
try
{
FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));
//Create Workbook instance holding reference to .xlsx file
Workbook workbook = new HSSFWorkbook(x);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
Row row = (Row) iterator.next();
for (Iterator<Cell> iterator2 = row.iterator(); iterator2
.hasNext();) {
Cell cell = (Cell) iterator2.next();
System.out.println(cell.getStringCellValue());
}
}
x.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
When using the apache poi 4.1.2. The celltype changes a bit. Below is an example
try {
File excel = new File("/home/name/Downloads/bb.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.
e.g
Sample code:
1.
//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cells iterator
Iterator itrat = ws.getCells().iterator();
//Print cells name in iterator
while(itrat.hasNext())
{
Cell cell = (Cell)itrat.next();
System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
This will write a JTable to a tab separated file that can be easily imported into Excel. This works.
If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.
This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
public class excel {
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
// Create some data
String dataValues[][] =
{
{ "12", "234", "67" },
{ "-123", "43", "853" },
{ "93", "89.2", "109" },
{ "279", "9033", "3092" }
};
JTable table;
excel() {
table = new JTable( dataValues, columnNames );
}
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static void main(String[] o) {
excel cv = new excel();
cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
}
}

Categories