Ok so I know you have to add the autoSizeColumns() method after you enter all your data into the sheet and workbook. And that is what I am doing but it is only resizing to the width of the last Cell entered??
public void writeFile() {
Workbook wb = new HSSFWorkbook();
Sheet s = wb.createSheet();
try {
FileOutputStream out = new FileOutputStream(
this.getSelectedFile());
// create a new workbook
// create a new sheet
// declare a row object reference
Row r = null;
// declare a cell object reference
Cell c = null;
// in case of plain ascii
wb.setSheetName(0, "Street Light Report");
// create a sheet with 30 rows (0-29)
// int rownum;
// short rownum;
// PrintWriter printOut = new PrintWriter(
// this.getSelectedFile());
String[] colName = { "Light Id", "Flagged",
"Malfunction", "Comments", "Location", "Date" };
// printOut.println("Light Id,Flagged,Malfunction,Comments,Location,Date");
Connections.connect();
String[][] data = Connections.searchForFlagged();
for (int i = 0; i < data.length; i++) {
r = s.createRow(i);
}
r.setRowNum(0);
for (int j = 0; j < 6; j++) {
c = r.createCell(j);
switch (j) {
case 0:
c.setCellValue(colName[j]);
break;
case 1:
c.setCellValue(colName[j]);
break;
case 2:
c.setCellValue(colName[j]);
break;
case 3:
c.setCellValue(colName[j]);
break;
case 4:
c.setCellValue(colName[j]);
break;
case 5:
c.setCellValue(colName[j]);
break;
}
}
for (int i = 0; i < data.length; i++) {
r.setRowNum(i + 1);
for (int j = 0; j < data[i].length; j++) {
c = r.createCell(j);
// System.out.println(data[i][j]);
switch (j) {
case 0:
c.setCellType(Cell.CELL_TYPE_NUMERIC);
c.setCellValue(Integer.parseInt(data[i][j]));
break;
case 1:
if (data[i][j].equals("true"))
c.setCellValue("Yes");
else
c.setCellValue("No");
break;
case 2:
if (data[i][j].equals("I"))
c.setCellValue("Intermittent");
else
c.setCellValue("Not Functional");
break;
case 3:
c.setCellValue(data[i][j]);
break;
case 4:
c.setCellValue(data[i][j]);
break;
case 5:
c.setCellValue(data[i][j]);
break;
}
}
}
wb.getSheetAt(0).setPrintGridlines(true);
for (int j = 0; j < 6; j++) {
s.autoSizeColumn(j);
}
wb.write(out);
out.close();
} catch (Exception ex) {
}
};
It seems that you do not have too many columns. Can you try defining each column like this:
sheet.autoColumnWidth(column number); //0 for the first column, 1 for the second, etc.
If that works then there is something wrong with your loop.
Related
So im trying to first copy the pivot table as values,
the values are already inserted, but then when i want to insert a specific row, above the pivot table values, sheet.createrow(0) replaces the previous row i don't know why. here is my code
for (int iSheet = 0; iSheet < sheets; iSheet++) {
sheet = workbook.getSheetAt(iSheet);
if (sheet != null) {
mySheet = myWorkBook.createSheet(sheet.getSheetName());
mySheet.createRow(0); //creating the first row
fRow = sheet.getFirstRowNum();
lRow = sheet.getLastRowNum();
for (int iRow = fRow; iRow <= lRow; iRow++) {
row = sheet.getRow(iRow);
myRow = mySheet.createRow(iRow);
if (row != null) {
fCell = row.getFirstCellNum();
lCell = row.getLastCellNum();
for (int iCell = fCell; iCell < lCell; iCell++) {
cell = row.getCell(iCell);
myCell = myRow.createCell(iCell);
if (cell != null) {
myCell.setCellType(cell.getCellType());
switch (cell.getCellType()) {
case BLANK:
myCell.setCellValue("");
break;
case BOOLEAN:
myCell.setCellValue(cell.getBooleanCellValue());
break;
case ERROR:
myCell.setCellErrorValue(cell.getErrorCellValue());
break;
case FORMULA:
myCell.setCellFormula(cell.getCellFormula());
break;
case NUMERIC:
myCell.setCellValue(cell.getNumericCellValue());
break;
case STRING:
myCell.setCellValue(cell.getStringCellValue());
break;
default:
myCell.setCellFormula(cell.getCellFormula());
}
}
}
}
}
}
}
I'm currently trying to merge two Excel files with each other. But there is a catch, I need to add between files the name of the file each file and an empty row. When I tried that, it added the name of the file and empty row but overwrote the first two rows of each file. How can I do it without losing first two rows of the file ?
public static void main(String[] args) {
try {
File firstFile = new File("/Users/TLQ/Desktop/report-12689-M2398-1.xlsx");
File secondFile = new File("/Users/TLQ/Desktop/report-12695-M2390-1.xlsx");
FileInputStream excellFile1 = new FileInputStream(firstFile);
FileInputStream excellFile2 = new FileInputStream(secondFile);
org.apache.poi.ss.usermodel.Workbook workbook1 = WorkbookFactory.create(excellFile1);
org.apache.poi.ss.usermodel.Workbook workbook2 = WorkbookFactory.create(excellFile2);
org.apache.poi.ss.usermodel.Sheet sheet1a = workbook1.getSheetAt(0);
org.apache.poi.ss.usermodel.Sheet sheet2a = workbook2.getSheetAt(0);
addSheet(sheet1a, sheet2a,secondFile.getAbsolutePath().substring(secondFile.getAbsolutePath().lastIndexOf("/")+1, secondFile.getAbsolutePath().indexOf(".")));
excellFile1.close();
// save merged file
File mergedFile = new File(
"/Users/TLQ/Desktop/Albert_1.xlsx");
if (!mergedFile.exists()) {
mergedFile.createNewFile();
}
FileOutputStream out = new FileOutputStream(mergedFile);
workbook1.write(out);
out.close();
System.out.println(firstFile.getAbsolutePath().substring(firstFile.getAbsolutePath().lastIndexOf("/")+1, firstFile.getAbsolutePath().indexOf(".")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addSheet(org.apache.poi.ss.usermodel.Sheet mergedSheet, org.apache.poi.ss.usermodel.Sheet sheet,String name) {
// map for cell styles
Map<Integer, org.apache.poi.ss.usermodel.CellStyle> styleMap = new HashMap<Integer, org.apache.poi.ss.usermodel.CellStyle>();
org.apache.poi.ss.usermodel.Row row2 = mergedSheet.createRow((short) 0);
org.apache.poi.ss.usermodel.Cell mcell2 = row2.createCell((short) 0);
mcell2.setCellValue("report-12689-M2398-1.xlsx");
// This parameter is for appending sheet rows to mergedSheet in the end
org.apache.poi.ss.usermodel.Row row1 = sheet.createRow((short) 0);
org.apache.poi.ss.usermodel.Cell mcell = row1.createCell((short) 0);
mcell.setCellValue(name);
org.apache.poi.ss.usermodel.Row row1Empty = sheet.createRow((short) 0);
org.apache.poi.ss.usermodel.Cell mcellEmpty = row1.createCell((short) 0);
int len = mergedSheet.getLastRowNum();
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
org.apache.poi.ss.usermodel.Row row = sheet.getRow(j);
org.apache.poi.ss.usermodel.Row mrow = mergedSheet.createRow(len + j + 1);
try {
for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
org.apache.poi.ss.usermodel.Cell cell=null;
if(row.getCell(k)!=null){
cell = row.getCell(k);
}else{
cell= row.createCell(k);
}
mcell = mrow.createCell(k);
if (cell.getSheet().getWorkbook() == mcell.getSheet()
.getWorkbook()) {
mcell.setCellStyle(cell.getCellStyle());
} else {
int stHashCode = cell.getCellStyle().hashCode();
org.apache.poi.ss.usermodel.CellStyle newCellStyle = styleMap.get(stHashCode);
if (newCellStyle == null) {
newCellStyle = mcell.getSheet().getWorkbook()
.createCellStyle();
newCellStyle.cloneStyleFrom(cell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
mcell.setCellStyle(newCellStyle);
}
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
mcell.setCellFormula(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
mcell.setCellValue(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
mcell.setCellValue(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
mcell.setCellType(HSSFCell.CELL_TYPE_BLANK);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
mcell.setCellValue(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
mcell.setCellErrorValue(cell.getErrorCellValue());
break;
default:
mcell.setCellValue(cell.getStringCellValue());
break;
}
}
} catch (Exception e) {
}
}
}
no sure which one the good but try
workbook1.write(out,true);
or workbook1.write(out,false);
it should set the fact to delete what was before or not.(true should be not erase what you got)
hope it help ;)
I am using POI to read excel file and convert it to a two-dimensional array. Following is code section:
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.CellValue;
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 XlsxRead_2 {
public XlsxRead_2(){
getvalue_1();
}
public static void getvalue_1(){
XSSFRow row;
XSSFCell cell;
String [][] value =null;
double[][] nums =null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//get sheet number
int sheetCn = workbook.getNumberOfSheets();
for(int cn = 0; cn < sheetCn; cn++){
//get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
//get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
//get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
value = new String[rows][cells];
nums= new double [rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value [r][c]= cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value [r][c]= "" + cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value [r][c]= "" + cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value [r][c]= "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value [r][c]= "" + cell.getErrorCellValue();
break;
default:
}
System.out.print(value);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Starter {
public static void main(String[] args) {
XlsxRead_2 gv=new XlsxRead_2();
}
}
However, it didn't work properly. Attached is wrong result in JAVA. When i worked it without using array, it work properly. Any suggestions is appreciated.
Result in java:
[[Ljava.lang.String;#167fdd33[[Ljava.lang.String;#1e965684
[[Ljava.lang.String;#4d95d2a2[[Ljava.lang.String;#53f65459
[[Ljava.lang.String;#3b088d51[[Ljava.lang.String;#1786dec2
[[Ljava.lang.String;#74650e52[[Ljava.lang.String;#15d0c81b
[[Ljava.lang.String;#6acdbdf5[[Ljava.lang.String;#4b1c1ea0
[[Ljava.lang.String;#3712b94[[Ljava.lang.String;#2833cc44
[[Ljava.lang.String;#33f88ab[[Ljava.lang.String;#27a8c74e
You should create array after first for loop. And also you should create values array for each sheet. And one more point you should print value[r][c] not value
I hope that helps you.
public class XlsxRead_2 {
public static void main(String[] args) {
XlsxRead_2 xread2 = new XlsxRead_2();
}
public XlsxRead_2() {
getvalue_1();
}
public static void getvalue_1() {
XSSFRow row;
XSSFCell cell;
String[][] value = null;
double[][] nums = null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// get sheet number
int sheetCn = workbook.getNumberOfSheets();
for (int cn = 0; cn < sheetCn; cn++) {
// get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
// get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
// get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
value = new String[rows][cells];
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
nums = new double[rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value[r][c] = cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value[r][c] = ""
+ cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value[r][c] = ""
+ cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value[r][c] = "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value[r][c] = ""+cell.getErrorCellValue();
break;
default:
}
System.out.print(value[r][c]);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to read the data from an excel file which has formulas and writing the data to a particular column of another excel but by using the below code, i am getting an error message like : Cannot Convert from void to HSSFCell at line 68.
#Test
public void SampleCustNumFormat() throws Exception {
String [] myXL = getExcelData();
//Write Data into Excel.
//See what has been read from Excel
System.out.println (" Before Loop " + myXL[1]);
for (int i=0; i<xRows; i++){
System.out.println (" Cust Num " + myXL[i]);
}
FileOutputStream out = new FileOutputStream ("C:\\SCE docs\\Automation\\TestExcelData.xls");
HSSFWorkbook myWB = new HSSFWorkbook();
HSSFSheet sheet = myWB.getSheetAt(0);
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
myWB.write(out);
out.close();
}
public String [] getExcelData() throws Exception{
String [] tabArray=null;
FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
HSSFWorkbook myWB = new HSSFWorkbook(fi);
HSSFSheet mySheet = myWB.getSheetAt(0);
FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();
xRows = mySheet.getLastRowNum()+1;
tabArray = new String [xRows];
for (int i=0;i<xRows;i++)
{
HSSFRow row = mySheet.getRow(i);
HSSFCell cell = row.getCell(3);
CellValue cellValue = evaluator.evaluate(cell);
String value = evaluateFormula(cellValue);
tabArray[i]=value;
}
return tabArray;
}
private String evaluateFormula(CellValue cellValue) throws Exception{
int type = cellValue.getCellType();
Object result=null;
switch (type) {
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cellValue.getBooleanValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cellValue.getNumberValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case HSSFCell.CELL_TYPE_FORMULA:
break;
}
return result.toString();
}
}
These lines are causing the trouble:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
Here you are getting the first row out of the sheet, creating a cell at index 2 and then setting the cell value... and assigning all of that to a Cell! However, setCellValue returns a void (as seen in the API). So basically, you need to split those lines into two like this:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2);
cell.setCellValue(myXL[k]);
}
Doing it this way, you'll first create the cell and assign that to cell. Then, you can set the value.
Edit: Alternatively, you can (as pointed out by Sankumarsingh) just not assign that value and do it all in one line like this:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
After Akoksis, I have to reframe your programe. please check it out whether its working or not for you
#Test
public void SampleCustNumFormat() throws Exception {
FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
HSSFWorkbook myWB = new HSSFWorkbook(fi);
HSSFSheet mySheet = myWB.getSheetAt(0);
String [] myXL = getExcelData(myWB);
//See what has been read from Excel
System.out.println (" Before Loop " + myXL[1]);
for (int i=0; i<xRows; i++){
System.out.println (" Cust Num " + myXL[i]);
}
FileInputStream file = new FileInputStream("C:\\SCE docs\\Automation\\TestExcelData.xls");
HSSFWorkbook wb = new HSSFWorkbook(file);
for (int k=1; k<=sheet.getLastRowNum(); k++){
wb.getSheet(0).getRow(1).createCell(2).setCellValue(myXL[k]);
}
//Write Data into Excel.
FileOutputStream out = new FileOutputStream ("C:\\SCE docs\\Automation\\TestExcelData.xls");
wb.write(out);
out.close();
}
public String [] getExcelData(HSSFWorkbook myWB) throws Exception{
String [] tabArray=null;
HSSFSheet mySheet = myWB.getSheetAt(0);
FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();
xRows = mySheet.getLastRowNum()+1;
tabArray = new String [xRows];
for (int i=0;i<xRows;i++){
HSSFRow row = mySheet.getRow(i);
HSSFCell cell = row.getCell(3);
CellValue cellValue = evaluator.evaluate(cell);
String value = evaluateFormula(cellValue);
tabArray[i]=value;
}
return tabArray;
}
private String evaluateFormula(CellValue cellValue) throws Exception{
int type = cellValue.getCellType();
Object result=null;
switch (type) {
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cellValue.getBooleanValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cellValue.getNumberValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case HSSFCell.CELL_TYPE_FORMULA:
break;
}
return result.toString();
}
}
This question already has answers here:
Apache POI autoSizeColumn Resizes Incorrectly
(10 answers)
Closed 9 years ago.
I am creating a program that writes information to an excel file using the apache poi. After I enter all of my data into the file I call the autoSizeColumn method on every column of the file. But it resizes the columns to the width of the last cell entered which is sometime not as big as the other cells in the column. I know I'm using it right and unfortunately I don't have Internet right now to post any code but I will update when I can.
Ok I hope I am using the code tags right but here it is :
public void writeFile() {
Workbook wb = new HSSFWorkbook();
Sheet s = wb.createSheet();
try {
FileOutputStream out = new FileOutputStream(
this.getSelectedFile());
// create a new workbook
// create a new sheet
// declare a row object reference
Row r = null;
// declare a cell object reference
Cell c = null;
// in case of plain ascii
wb.setSheetName(0, "Street Light Report");
// create a sheet with 30 rows (0-29)
// int rownum;
// short rownum;
// PrintWriter printOut = new PrintWriter(
// this.getSelectedFile());
String[] colName = { "Light Id", "Flagged",
"Malfunction", "Comments", "Location", "Date" };
// printOut.println("Light Id,Flagged,Malfunction,Comments,Location,Date");
Connections.connect();
String[][] data = Connections.searchForFlagged();
for (int i = 0; i < data.length; i++) {
r = s.createRow(i);
}
r.setRowNum(0);
for (int j = 0; j < 6; j++) {
c = r.createCell(j);
switch (j) {
case 0:
c.setCellValue(colName[j]);
break;
case 1:
c.setCellValue(colName[j]);
break;
case 2:
c.setCellValue(colName[j]);
break;
case 3:
c.setCellValue(colName[j]);
break;
case 4:
c.setCellValue(colName[j]);
break;
case 5:
c.setCellValue(colName[j]);
break;
}
}
for (int i = 0; i < data.length; i++) {
r.setRowNum(i + 1);
for (int j = 0; j < data[i].length; j++) {
c = r.createCell(j);
// System.out.println(data[i][j]);
switch (j) {
case 0:
c.setCellType(Cell.CELL_TYPE_NUMERIC);
c.setCellValue(Integer.parseInt(data[i][j]));
break;
case 1:
if (data[i][j].equals("true"))
c.setCellValue("Yes");
else
c.setCellValue("No");
break;
case 2:
if (data[i][j].equals("I"))
c.setCellValue("Intermittent");
else
c.setCellValue("Not Functional");
break;
case 3:
c.setCellValue(data[i][j]);
break;
case 4:
c.setCellValue(data[i][j]);
break;
case 5:
c.setCellValue(data[i][j]);
break;
}
}
}
wb.getSheetAt(0).setPrintGridlines(true);
for (int j = 0; j < 6; j++) {
s.autoSizeColumn(j);
}
wb.write(out);
out.close();
} catch (Exception ex) {
}
};
I would post an image here but I need rep. point and I just started here.
** Note that the Connections class is the JDBC class so that java can pull the information from th mySQL database it returns a 2D array of strings **
You just need to move the call to
sheet.autoSizeColumn(columnNumber);
to a point in your code after the data has been added.
Here is a link to the API
That's the only way to do it. I had same problem, I was calling the method autoSizeColumn() before I entered the data. Hop it helped
Move the for loop :
for (int j = 0; j < 6; j++) {
s.autoSizeColumn(j);
}
to be just before you write in the workbook and close your out object.
wb.write(out);