I am using Apache POI and Java to take an SQL query and format the data and put it into two separate sheets. The first sheet works fine but it never loads data into the second sheet. I've tried just using the code for the second sheet and it works as long as the first sheets code is commented out. This leads me to believe it is caused by my poor java code.
Code is below
public static void createSheet1(ResultSet rs3) throws SQLException, FileNotFoundException {
Desktop dt = Desktop.getDesktop();
//CREATE WORKBOOK
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Run Tickets");
int i=0;
while (rs3.next()){
if (i <= 0){
XSSFRow rowhead = sheet.createRow((short)0);
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont defaultFont = workbook.createFont();
defaultFont.setBold(true);
defaultFont.setFontHeight(13);
style.setFont(defaultFont);
rowhead.createCell((short) 0).setCellValue("ROUTE_NAME");
rowhead.createCell((short) 1).setCellValue("STOP_NAME");
rowhead.createCell((short) 2).setCellValue("EQUIP_NAME");
rowhead.createCell((short) 3).setCellValue("DESTINATION");
rowhead.createCell((short) 4).setCellValue("PURCHASER");
rowhead.createCell((short) 5).setCellValue("Ticket DT");
rowhead.createCell((short) 6).setCellValue("Ticket #");
rowhead.createCell((short) 7).setCellValue("EQUIP_TYPE");
rowhead.createCell((short) 8).setCellValue("OPEN_FEET");
rowhead.createCell((short) 9).setCellValue("OPEN_INCH");
rowhead.createCell((short) 10).setCellValue("OPEN_TMP");
rowhead.createCell((short) 11).setCellValue("CLOSE_FEET");
rowhead.createCell((short) 12).setCellValue("CLOSE_INCH");
rowhead.createCell((short) 13).setCellValue("CLOSE_TMP");
rowhead.createCell((short) 14).setCellValue("OBSV_GRAV");
rowhead.createCell((short) 15).setCellValue("OBSV_TMP");
rowhead.createCell((short) 16).setCellValue("BSW");
rowhead.createCell((short) 17).setCellValue("CLOSE_DT");
rowhead.createCell((short) 18).setCellValue("OPEN_VOLUME");
rowhead.createCell((short) 19).setCellValue("CLOSE_VOLUME");
rowhead.createCell((short) 20).setCellValue("GROSS_VOLUME");
rowhead.createCell((short) 21).setCellValue("NET_VOLUME");
rowhead.createCell((short) 22).setCellValue("STATION_NAME");
for(int j =0; j<23;j++){
rowhead.getCell(j).setCellStyle(style);
}
}
else{
XSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs3.getString("ROUTE_NAME"));
row.createCell((short) 1).setCellValue(rs3.getString("STOP_NAME"));
row.createCell((short) 2).setCellValue(rs3.getString("EQUIP_NAME"));
row.createCell((short) 3).setCellValue(rs3.getString("COMMENTS"));
row.createCell((short) 4).setCellValue(rs3.getString("BA_NAME"));
row.createCell((short) 5).setCellValue(rs3.getString("LQVOL_DT"));
row.createCell((short) 6).setCellValue(rs3.getString("LQVOL_TRANS"));
row.createCell((short) 7).setCellValue(rs3.getString("EQUIP_TYPE"));
row.createCell((short) 8).setCellValue(rs3.getInt("OPEN_FEET"));
row.createCell((short) 9).setCellValue(rs3.getInt("OPEN_INCH"));
row.createCell((short) 10).setCellValue(rs3.getInt("OPEN_TMP"));
row.createCell((short) 11).setCellValue(rs3.getInt("CLOSE_FEET"));
row.createCell((short) 12).setCellValue(rs3.getInt("CLOSE_INCH"));
row.createCell((short) 13).setCellValue(rs3.getInt("CLOSE_TMP"));
row.createCell((short) 14).setCellValue(rs3.getInt("OBSV_GRAV"));
row.createCell((short) 15).setCellValue(rs3.getInt("OBSV_TMP"));
row.createCell((short) 16).setCellValue(rs3.getInt("BSW"));
row.createCell((short) 17).setCellValue(rs3.getString("CLOSE_DT"));
row.createCell((short) 18).setCellValue(rs3.getInt("OPEN_VOLUME"));
row.createCell((short) 19).setCellValue(rs3.getInt("CLOSE_VOLUME"));
row.createCell((short) 20).setCellValue(rs3.getInt("GROSS_VOLUME"));
row.createCell((short) 21).setCellValue(rs3.getInt("NET_VOLUME"));
row.createCell((short) 22).setCellValue(rs3.getString("STATION_NAME"));
}
++i;
}
//AUTOSIZE COLUMNS
int j =0;
while(j<23)
{
sheet.autoSizeColumn(j);
j++;
}
createSheet2(rs3,workbook, dt);
outputExcel(workbook, dt);
}
public static XSSFWorkbook createSheet2(ResultSet rs3, XSSFWorkbook workbook, Desktop dt2) throws SQLException, FileNotFoundException {
//CREATES SECOND SHEET "ALLOCATION"
XSSFSheet sheet2 = workbook.createSheet("Allocation");
int rowcnt = 0;
while(rs3.next()){
if(rowcnt == 0){
XSSFRow rowhead2 = sheet2.createRow((short)0);
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont defaultFont = workbook.createFont();
defaultFont.setBold(true);
defaultFont.setFontHeight(13);
style.setFont(defaultFont);
rowhead2.createCell((short) 0).setCellValue(rs3.getString("STATION_NAME"));
}
rowcnt++;
}
return workbook;
}
public static void outputExcel(XSSFWorkbook workbook, Desktop dt) throws FileNotFoundException {
String yemi = "M:/MonthlyEndClosing.xlsx";
FileOutputStream fileOut = new FileOutputStream(yemi);
try {
workbook.write(fileOut);
fileOut.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
dt.open(new File("M:/MonthlyEndClosing.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried this in just one method,separate classes and now in two methods with the same results. I appreciate any help you can give.
Your problem is not in POI API using but in your resultSet :
while (rs3.next()){
...
}
//rs3.next() will now be false
Related
When I download Excel, I get cells with format Numbers I need format text en all Cells.
try {
XSSFSheet sheet = workbook.createSheet(eyelash);
XSSFFont font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.RED.index);
String[] header = { "name","surname"};
XSSFRow rowhead = sheet.createRow((short) 0);
XSSFCell cell;
int cellnum = 0;
for (int i = 0; i < header.length; i++) {
cell = rowhead.createCell(cellnum);
cell.setCellValue(header[i]);
cell.setCellStyle(style);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cellnum++;
}
if (data) {
int myRowData = 1;
XSSFRow row = sheet.createRow((short) myRowData);
ArrayList<GasNomination> list = this.select();
for (int i = 0; i < list.size(); i++) {
row.createCell(0).setCellValue(list.get(i).name());
row.createCell(1).setCellValue(list.get(i).surname());
myRowData++;
row = sheet.createRow((short) myRowData);
}
}
} catch (Exception ex) {
}
I tried cell.setCellType(XSSFCell.CELL_TYPE_STRING);
But when I open my Excel I see formatcell type numeric ...
You can use DataFormatter,
System.out.println("started");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue(3.14159);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
XSSFDataFormat format = workbook.createDataFormat();
XSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("Text"));
cell.setCellStyle(style);
workbook.write(new FileOutputStream("Test.xlsx"));
System.out.println("finished");
String filepath="";
try {
//String filename=file_name.replace('/','_');
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(file_name);
HSSFRow rowhead = sheet.createRow((short) 0);
filepath=prop.getProperty("file_store_path")+file_name+timeStamp+".xls";
FileOutputStream fileOut = new FileOutputStream(filepath);
/* rowhead.createCell((short) 1).setCellValue("Domain ID");*/
rowhead.createCell((short) 0).setCellValue("Person ID");
rowhead.createCell((short) 1).setCellValue("Domain ID");
rowhead.createCell((short) 2).setCellValue("First Name");
rowhead.createCell((short) 3).setCellValue("Last Name");
rowhead.createCell((short) 4).setCellValue("Email Address");
rowhead.createCell((short) 5).setCellValue("SBU");
int i = 1;
while (rs.next()){
HSSFRow row = sheet.createRow((short) i);
/* row.createCell((short) 0).setCellValue(rs.getString("domain_id"));*/
row.createCell((short) 0).setCellValue(rs.getString("person_id"));
row.createCell((short) 1).setCellValue(rs.getString("domain_id"));
row.createCell((short) 2).setCellValue(rs.getString("first_name") );
row.createCell((short) 3).setCellValue(rs.getString("last_name"));
row.createCell((short) 4).setCellValue(rs.getString("email_address"));
row.createCell((short) 5).setCellValue(rs.getString("business_unit"));
i++;
}
workbook.write(fileOut);
fileOut.close();
System.out.println("XLS done!!");
}
I am having some issue with excel sheet exporting in Server side. The sheet is working fine in local but not working when deploying in Server. I am using XSSF format here (I have also used HSSF but getting different issue with that). I have attached the error message here.
How can I solve this issue?
The error I am getting is
java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(Unknown Source)
at com.controllers.ActiveUserReport.getDownloaded(ActiveUserReport.java:308)
at com.controllers.ActiveUserReport.doGet(ActiveUserReport.java:113)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
How to populate an Excel sheet with the data from an arraylist using Apache POI?
public String exporttoexcel(UserDetails user) throws Exception {
System.out.print("Inside serviceimpl.ExportToExcel method");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
List<UserDetails> lstUserDetail = getUserDetailList();
for (int i=0; i<lstUserDetail.size(); i++) {
UserDetails lstUserDetail1 = lstUserDetail.get(i);
String a=lstUserDetail1.getStrUserName();
System.out.print("useridddd is"+a);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(lstUserDetail1.getStrUserId());
cell.setCellValue(lstUserDetail1.getStrUserName());
cell.setCellValue(lstUserDetail1.getStrEMail());
cell.setCellValue(lstUserDetail1.getStrUserStatus());
cell.setCellValue(lstUserDetail1.getStrUserRole());
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("file created");
return null;
}
You have created one single cell and entering all the values in a same single cell each time.
You need to take two loops. One for iterating through row and another for iterating through column. Though I have not tested... use code like below.
for(int RowNum=0; RowNum<MaxArrayLength;RowNum++){
HSSFRow row = sheet.createRow(RowNum);
for(int ColNum=0; ColNum<ArrayWidth;ColNum++){
HSSFCell cell = row.createCell(ColNum);
cell.setCellValue(ArrayList[RowNum][ColNum]);
}
}
FileOutputStream fileOut = new FileOutputStream("your file path");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet name");
try {
//creating the headers
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("name");
row.createCell(1).setCellValue("Name1");
row.createCell(2).setCellValue("name2");
//get the list which u want
List<String> list = getNamesList();
int rowNum = 1;
for (Name name : list ) {
Row row1 = sheet.createRow(rowNum++);
row1.createCell(0).setCellValue((name.get..));
}
workbook.write(fileOut);
}
I am doing a java application (J2SE) which I have to generate a excel document (.xls). I did generate the file but I am not able to change the cell width dynamically according to the content which is having the maximum length in the same cell.
Here is my coding...
try {
ResultSet rs = com.dss.system.DBORCL.search("sql statement");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("Site");
rowhead.createCell((short) 1).setCellValue("Part No");
rowhead.createCell((short) 2).setCellValue("Part Description");
int index = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) index);
row.createCell((short) 0).setCellValue(rs.getString("site"));
row.createCell((short) 1).setCellValue(rs.getString("part_no"));
row.createCell((short) 1).setCellValue(rs.getString("description"));
index++;
}
FileOutputStream fileOut = new FileOutputStream("F:\\IFS\\IFSDOC" + txtPLCode.getText() + "[" + currentDate + "-" + usesecond + "]" + ".xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
// rs.close();
sheet.autoSizeColumn(0) //for first column
sheet.autoSizeColumn(1) //for second column ... etc
Refer: http://poi.apache.org/spreadsheet/quick-guide.html#Autofit
I am exporting data displayed in jqgrid into .excel file by clicking button .
Here is my code for export to excel button click..
$('#excel').click(function(){
var fromdate=$('#fromdate').val();
var todate=$('#todate').val();
if(fromdate && todate)
{
var URL='excel?fromdate='+$('#fromdate').val()+'&todate='+$('#todate').val();
$.ajax({
url:URL,
type:'GET',
success:function(data){
alert('Exported To Excel');
}
});
}
});
Now this button will direct to excel.java page which is servlet.Below is my exceljava page code .Now Asper my need when the user click on export to excel button a openwith and save as dialogue box should popup which gives user ability to give desired name and save to desired positionbut it is not happening with this code.plz point out my mistake ..
excel.java
try {
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=excel.xls");
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
rowhead.createCell((short) 3).setCellValue("dstchannel");
rowhead.createCell((short) 4).setCellValue("lastapp");
rowhead.createCell((short) 5).setCellValue("duration");
rowhead.createCell((short) 6).setCellValue("disposition");
rowhead.createCell((short) 7).setCellValue("amaflags");
rowhead.createCell((short) 8).setCellValue("cdrcost");
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
//strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";
rs = conexiondb.Consulta(strQuery);
int i = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
row.createCell((short) 3).setCellValue(rs.getString("dstchannel"));
row.createCell((short) 4).setCellValue(rs.getString("lastapp"));
row.createCell((short) 5).setCellValue(rs.getString("duration"));
row.createCell((short) 6).setCellValue(rs.getString("disposition"));
row.createCell((short) 7).setCellValue(rs.getString("amaflags"));
row.createCell((short) 8).setCellValue(rs.getString("cdrcost"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
hwb.write(response.getOutputStream());
System.out.println("Your excel file has been generated!");
FileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}