I am trying to write data into excel through the web tables.
starting rows get created with blank data and last row is filled with data, with last index value.
other rows are not getting filled with data even when data is present in the Arraylist.
public class Write_Excel {
public static `FileInputStream` `fis`;
public static FileOutputStream fos;
public static `HSSFWorkbook` `wb`;
public static `HSSFSheet` `sheet`;
public static `HSSFCell` `cell`;
public static `HSSFRow` `row`;
public static `int a = 0`;
public static void write_Excel(String fileName, String sheetName,
`ArrayList`<String> `dataToWrite`) throws `IOException` {
fos = new `FileOutputStream(fileName);
wb = new HSSFWorkbook();
sheet = `wb.createSheet(sheetName);`
`row = sheet.createRow(a++);`
for (int i = 0; i < 16; i++) {
cell = row.createCell(i);
System.out.println(dataToWrite.get(i).toString());
cell.setCellValue(new HSSFRichTextString(dataToWrite.get(i)));
}
wb.write(fos);
fos.flush();
}
}
You should add this line into for loop
HSSFRow row = sheet.createRow(a++);
As you do it, you create a new workbook every time you call the function and you just end up erasing the previous ones. Therefore you only get the result of the last call.
If you want to add a line at every call, do it this way, you need to have the row number and the workbook as class variables. Also you need to get hold of the sheet that you already created to append to it. or you are going to erase it too.
public static void main(String[] args) {
try {
write_Excel("myFile.xls","sheetName",
Arrays.asList("value 1", "value 2", "value 3"));
write_Excel("myFile.xls","sheetName",
Arrays.asList("value 4", "value 5", "value 6"));
} catch(IOException e) {
e.printStackTrace();
}
}
private static int newRowIndex = 0;
private static HSSFWorkbook workbook = new HSSFWorkbook();
public static void write_Excel(String fileName, String sheetName, List<String> dataToWrite) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
// open or create sheet
HSSFSheet sheet = workbook.getSheet(sheetName) != null ?
workbook.getSheet(sheetName) :
workbook.createSheet(sheetName);
// create a new row
HSSFRow row = sheet.createRow(newRowIndex ++);
// write your data in the new row
for (int colIndex = 0; colIndex < dataToWrite.size(); colIndex++) {
HSSFCell cell = row.createCell(colIndex);
cell.setCellValue(new HSSFRichTextString(dataToWrite.get(colIndex)));
}
workbook.write(fos);
fos.flush();
fos.close();
}
Related
I am a beginner in java and Apache POI.
So right now what i wanna to achieve is I want to loop the array days row by row(vertical) under the Days column:
Public Holidays Days Date Class
public static void main(String[] args) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
String[] days = { "SU", "MO", "TU", "WED", "TH", "FR", "SA" };
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("Public Holidays");
row.createCell(1).setCellValue("Days");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Class");
int numRows = sheet.getFirstRowNum();
int numCols = sheet.getRow(0).getLastCellNum();
for (int i = 1; i < 7; i++) {
Row row2 = sheet.createRow(i);
Cell cell = row.createCell(1);
cell.setCellValue(days);
}
try {
FileOutputStream out = new FileOutputStream(new File("C:xx"));
workbook.write(out);
out.close();
System.out.print("Sucess, please check the file");
} catch (Exception e) {
e.printStackTrace();
}
}
The error that I am getting is that:
The method setCellValue(double) in the type Cell is not applicable for the arguments (String[])
Please help me solve this array problem.
The method setCellValue(double) in the type Cell is not applicable for the arguments (String[])
You attempted to pass a String array declared as
String[] days = { "SU", "MO",...};
to the setCellValue() method. There is no overloaded variant of setCellValue() that accepts a String[] argument. I think you meant
cell.setCellValue(days[i-1]);
The error message is a little confusing because in trying to resolve the method it chose one (the one taking double) to indicate in the message.
public static void main(String[] args) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
String[] days = { "SU","MO", "TU", "WED", "TH", "FR", "SA"};
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("Public Holidays");
row.createCell(1).setCellValue("Days");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Class");
int numRows = sheet.getFirstRowNum() + 1;
for (int i = 1; i <= 7; i++) {
Row row2 = sheet.createRow(i);
Cell cell = row2.createCell(1);
cell.setCellValue(days[i - 1]);
}
try {
FileOutputStream out = new FileOutputStream(new File("C:xx"));
workbook.write(out);
out.close();
System.out.print("Sucess, please check the file");
} catch (Exception e) {
e.printStackTrace();
}
}
here is the working file. thank you for helping me :D
Please excuse me if I am not clear. English is not my first language.
I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?
public static void main(String[] args) throws IOException {
File myFile = new File("temp.xlsx");
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#SuppressWarnings("resource")
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String comment = cell.toString();
if (comment.equals("Comments"))
{
System.out.println("Hello");
}
}
}
}
For the question "Wanted to go to the second column's 3rd row I could use coordinates like (3, 2)?":
Yes this is possible using CellUtil. Advantages over the methods in Sheet and Row are that CellUtil methods are able getting the cell if it exists already or creating the cell if it not already exists. So existing cells will be respected instead simply new creating them and so overwriting them.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.concurrent.ThreadLocalRandom;
public class CreateExcelCellsByIndex {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
//put content in R3C2:
Cell cell = CellUtil.getCell(CellUtil.getRow(3-1, sheet), 2-1); //-1 because apache poi's row and cell indexes are 0 based
cell.setCellValue("R3C2");
//put content in 10 random cells:
for (int i = 1; i < 11; i++) {
int r = ThreadLocalRandom.current().nextInt(4, 11);
int c = ThreadLocalRandom.current().nextInt(1, 6);
cell = CellUtil.getCell(CellUtil.getRow(r-1, sheet), c-1);
String cellcontent = "";
if (cell.getCellTypeEnum() == CellType.STRING) {
cellcontent = cell.getStringCellValue() + " ";
}
cell.setCellValue(cellcontent + i + ":R"+r+"C"+c);
}
workbook.write(new FileOutputStream("CreateExcelCellsByIndex.xlsx"));
workbook.close();
}
}
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING: ... break;
case NUMERIC: ... break;
case BOOLEAN: ... break;
case FORMULA: ... break;
default: data.get(new Integer(i)).add(" ");
}
}
i++;
}
I'm not sure what you mean by 2D index, but a Cell knows which column it belongs to so something like this should work:
...
Cell cell = cellIterator.next();
String comment = cell.toString();
int sourceColumnIndex = -1;
if (comment.equals("Comments")) {
System.out.println("Hello");
sourceColumnIndex = cell.getColumnIndex();
}
....
Similarly, define something like int targetColumnIndex to represent the column which will have the result from processing all the cells from the sourceColumnIndex column.
I want to create an excel document with 5 sheets, the data for the sheets is dynamic and I have a maximum row limit.
currently my approach is creating one sheet at a time, and filling it with data. I am checking if max rows have been exceeded, and creating a new excel document.
However this will not wait to check if the other sheets are also exceeding the max row limit before creating the new workbook
My code samples
private void populateDetailsSheets(String[] data) throws IOException
{
currentRow = getCurrentRow();
rowCount++;
short cellNumber = 0;
for (String value : data)
{
POIExcelUtil.createCellWithContent(currentRow,value,cellNumber++).setCellStyle(contentStyle);
}
writeToFileOnExhaustingMaxRows();
}
private void writeToFileOnExhaustingMaxRows() throws IOException
{
if(sheet.getLastRowNum() + 2 > Integer.valueOf(SystemProperty.MAX_RECORDS_PER_EXCEL))
{
writeToFile();
rowCount = 0;
createWorkbook();
titleStyle = createTitleStyle();
headerStyle = createHeaderStyle();
columnHeaderStyle = createColumnHeaderStyle();
columnHeaderStyle.setBorderLeft(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderRight(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);
contentStyle = createCellStyle();
contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
contentStyle.setBorderTop(CellStyle.BORDER_THIN);
contentStyle.setBorderRight(CellStyle.BORDER_THIN);
contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
rowCount = 0;
createSheet("title sheet");
populateReportSettingsSheet();
rowCount =0;
createSheet(sheetNames[index]);
setColumnWidth();
createColumnHeader();
}
}
I am assuming that you want to jump to next sheet when the sheet one is full. Here the trick.
public class JumpToNewSheet {
private static HSSFSheet allocateNewSheet(HSSFWorkbook wb, String sheetName) {
HSSFSheet sheet = wb.createSheet(sheetName);
/*You can add style here too or write header here*/
return sheet;
}
public HSSFWorkbook exportExcel_xls(MyTable table) {
int cellNumber = 12;
List<TupleData> tuples = table.getTuples();
HSSFWorkbook wb = new HSSFWorkbook();//Whole book
HSSFSheet currentSheet = allocateNewSheet(wb, "SHEET");//Initial sheet
int sheetCounter = 1;//Start at 1 because we already created Initial sheet
int rowCounter = 0;//1st row in sheet
for(TupleData t: tuples) {//Loop through data
if(rowCounter % 65535 == 0) {//Max row reached, build new sheet
//Increase sheetCounter
sheetCounter++;
String new_sheetName = "SHEET_"+sheetCounter;//Name of sheet
currentSheet = allocateNewSheet(wb, new_sheetName);//Point currentSheet to new sheet
//Reset rowCounter to 0
rowCounter = 0;
}
Row row = currentSheet.createRow(rowCounter);
for(int i=0; i <=cellNumber; i++) {
Cell cell = row.createCell(i);
//Write data.......
//.............
}//End inner for loop
rowCounter++;
}//End for loop
}//End exportExcel_xls(MyTable table)
}
public class sample {
private static Workbook workbook;
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C://Users//chakku//Desktop//ch//updated/TestReport Lang Funda1.xls");
workbook = new HSSFWorkbook(fis);
Sheet sh = workbook.getSheetAt(0);
for(int i=0;i<=sh.getLastRowNum();i++) {
int z=i+1;
Cell cell = sh.getRow(z).getCell(1);
if(Cell.CELL_TYPE_BLANK == cell.getCellType()) {
System.out.println("3");
}else {
System.out.println(cell.getRichStringCellValue());
}
}
}catch(FileNotFoundException ex) {
ex.printStackTrace();
}catch(IOException ex) {
ex.printStackTrace();
}
}
}
I don't know what's wrong but at the end when all records are fetched it's printing NullPointerException
Error in constructing the access index - use this:
for(int z= 1;z<=sh.getLastRowNum();z++) {
if say you just have two rows, then sh.getLastRowNum() will return you one (as it starts count with 0), and you will try to access it like
for(int i=0;i<=sh.getLastRowNum();i++) {
int z=i+1;
Cell cell = sh.getRow(z).getCell(1);
So for i = 1, you are accessing 2nd row (sh.getRow(2)), which doesnt exists as you should start with 0th row. You should do the following:
for(int i=0;i<=sh.getLastRowNum();i++) {
Cell cell = sh.getRow(z).getCell(1);
I am trying to export data from a database to Excel. I have the data exported and currently being stored in an ArrayList (this can be changed). I have been able to export the data to excel but all of the values are being exported as Strings, I need them to keep their data type i.e currency/numeric.
I am using Apache POI and am having difficult with setting the data type of the fields to anything other than String. Am I missing something? Can someone please advise me on a better way of doing this? Any assistance on this would be greatly appreciated.
public static void importDataToExcel(String sheetName, ArrayList header, ArrayList data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsFilename));
HSSFSheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
short cellIdx = 0;
// Header
HSSFRow hssfHeader = sheet.createRow(rowIdx);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (Iterator cells = header.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue((String) cells.next());
}
// Data
rowIdx = 1;
for (Iterator rows = data.iterator(); rows.hasNext();) {
ArrayList row = (ArrayList) rows.next();
HSSFRow hssfRow = (HSSFRow) sheet.createRow(rowIdx++);
cellIdx = 0;
for (Iterator cells = row.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfRow.createCell(cellIdx++);
hssfCell.setCellValue((String) cells.next());
}
}
Logfile.log("sheetNumber = " + sheetNumber);
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
You need to check for the class of your cell value before you cast:
public static void importDataToExcel(String sheetName, List<String> headers, List<List<Object>> data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
Workbook wb;
try {
wb = WorkbookFactory.create(new FileInputStream(xlsFilename));
} catch (InvalidFormatException ex) {
throw new IOException("Invalid workbook format");
}
Sheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
int cellIdx = 0;
// Header
Row hssfHeader = sheet.createRow(rowIdx);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (final String header : headers) {
Cell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue(header);
}
// Data
rowIdx = 1;
for (final List<Object> row : data) {
Row hssfRow = sheet.createRow(rowIdx++);
cellIdx = 0;
for (Object value : row) {
Cell hssfCell = hssfRow.createCell(cellIdx++);
if (value instanceof String) {
hssfCell.setCellValue((String) value);
} else if (value instanceof Number) {
hssfCell.setCellValue(((Number) value).doubleValue());
} else {
throw new RuntimeException("Cell value of invalid type " + value);
}
}
}
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
I have also added in generics - this makes the code a lot more readable. Also you need to avoid using the actual class where possible and use the interface, for example List not ArrayList and Row not HSSFRow.