Eclipse - POI XSSF generates corrupted Workbook - java

Whenever I run this code, it creates or updates the existing xlsx spreadsheet and immediately corrupts it. I have tried to leave the file open before continuing but that does not help. This worked prior to our hosting provider forcing us to use an SSH tunnel to reach our MySQL server. Connectivity through SQL tools seems fine. The file is stored on the local machine (OneDrive).
JButton btnRecordCompletions = new JButton("Record Completions");
btnRecordCompletions.setBounds(26, 168, 156, 23);
btnRecordCompletions.setMnemonic(KeyEvent.VK_R);
panelReporting.add(btnRecordCompletions);
btnRecordCompletions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (realm == "Security") {
System.out.println("Realm is " + realm);
DateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date date1 = new java.util.Date();
System.out.println("Date is " + date1);
dateFormat1.format(date1);
String dateof = (new java.text.SimpleDateFormat("yyyy/MM/dd")).format(compdate.getDate());
String mark_complete = "SELECT DISTINCT wpgc.user_id, wpgc.timestamp\r\n"
+ "FROM wp_grassblade_completions as wpgc \r\n" + " INNER JOIN \r\n"
+ "wp_usermeta ON wpgc.user_id = wp_usermeta.user_id\r\n"
+ "WHERE wpgc.user_id NOT IN (SELECT atc_reporting.user_id FROM atc_reporting WHERE course = 'SECURITY') AND wpgc.timestamp BETWEEN (CURRENT_DATE -INTERVAL 30 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY) AND content_id IN (1575, 642, 1580) \r\n"
+ "GROUP BY wpgc.user_id\r\n" + "order BY wpgc.timestamp, wp_usermeta.user_id";
try {
FileInputStream inputstream = new FileInputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
int index0 = 0;
Workbook workbook = WorkbookFactory.create(inputstream);
XSSFSheet sheet0 = (XSSFSheet) workbook.getSheet("Security_Completions");
if (sheet0 != null) {
index0 = workbook.getSheetIndex(sheet0);
workbook.removeSheetAt(index0);
}
FileOutputStream output = new FileOutputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
workbook.write(output);
output.close();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3307/wp_dashort", "dashort",
"gt9wkk6r1TPnkgrY");
PreparedStatement ps = null;
ps = connection.prepareStatement(mark_complete);
dateof = dateof + " 00:00";
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
System.out.println("Executing Query");
Sheet sheet = workbook.createSheet("Security_Completions");
org.apache.poi.ss.usermodel.Row rowhead = sheet.createRow((short) 0);
System.out.println("Sheet created");
rowhead.createCell((short) 0).setCellValue("Column 1");
rowhead.createCell((short) 1).setCellValue("Column 2");
System.out.println("Number of records = " + size);
// Running thru the ResultSet
int index = 0;
int r = 0;
rs.next();
while (rs.next()) {
index = index + 1;
Row row = sheet.createRow((short) index);
for (int i = 0; i < 1; ++i) {
String value = rs.getString(1);
row.createCell(i).setCellValue(value);
row.createCell(1).setCellValue(StringUtils.left((rs.getString(2)), 16));
rs.next();
}
++r;
}
FileOutputStream fileOut = new FileOutputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();

Related

Corrupted Excel workbook after POI write from SQL results

I run the following class to generate an Excel spreadsheet that will contain the results of my SQL query. Each time the file is generated, there is an error message when you try to open it up, "Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
I am at the end of my abilities with respect to troubleshooting this as I have used this type of code successfully and have noticed this error arising after the switch to an SSH MySQL connection versus a straight 3306 connection previously. There are no error messages in the console.
package process;
import java.sql.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
public class WriteMySQLToExcel {
public static void main(String[] args) throws SQLException, IOException {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/wp_dashort", "dashort", "gt9wkk6r1TPnkgrY");
String mark_complete = "SELECT DISTINCT wpgc.user_id, wpgc.timestamp\r\n"
+ "FROM wp_grassblade_completions as wpgc \r\n" + " INNER JOIN \r\n"
+ " wp_usermeta ON wpgc.user_id = wp_usermeta.user_id\r\n"
+ " WHERE wpgc.user_id NOT IN (SELECT atc_reporting.user_id FROM atc_reporting WHERE course = 'SECURITY') AND wpgc.timestamp BETWEEN (CURRENT_DATE -INTERVAL 30 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY) AND content_id IN (1575, 642, 1580) \r\n"
+ "GROUP BY wpgc.user_id\r\n" + "order BY wpgc.timestamp, wp_usermeta.user_id";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(mark_complete);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Query Results");
// Create header row
XSSFRow headerRow = sheet.createRow(0);
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
headerRow.createCell(i - 1).setCellValue(rs.getMetaData().getColumnName(i));
}
int rowNum = 1;
while (rs.next()) {
XSSFRow row = sheet.createRow(rowNum++);
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
row.createCell(i - 1).setCellValue(rs.getString(i));
}
}
FileOutputStream fileOut = new FileOutputStream("D://testexpdata.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
rs.close();
stmt.close();
conn.close();
}
}
Code to connect through SSH follows:
public class SQLConnection {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
dataBaseName="wp_dashort";
connectSSH();
connectToDataBase(dataBaseName);
}
static void connectSSH() throws SQLException {
String sshHost = "shortguy.ssh.wpengine.net";
String sshuser = "shortguy";
String dbuserName = "shortguy";
String dbpassword = "gt9wgrYpassword";
String SshKeyFilepath = "c://users//ed25519eclipse";
int localPort = 3307; // any free port can be used
String remoteHost = "127.0.0.1";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.cj.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost:" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
POI 5.2.3
Apache Maven 3.8.7
MySQL Connector 8.0.32
XMLBeans 5.1.1
I put the versions at the bottom of the code block above.
Thanks again!

How do I separate Big chunk of code of JDBC into different classes?

I wrote a big chunk of codes that downloads CSV file from url, then i bulk inserted into sql database, then call data from SQL server and display on Java console. Finally select the column I want to keep and export as a new CSV file.
but all of those codes are in the same class right now. How can I separate them into different class like I want a class for just download file and another class just do the Bulk insert and another class to just do the Select Query.
Thanks for helping me out
below is my code in one class now
public class ProjectTest extends CreateTable {
public static void main(String[] args) throws MalformedURLException {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
URL url = new URL(
"https://quality.data.gov.tw/dq_download_csv.php?nid=43983&md5_url=9d38afbca8243a24b5b89d03a8070aff");
try (InputStream inputStream = url.openStream();
FileOutputStream fos = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\virus.csv");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost:1433;databaseName=JDBCDB", "andy3", "andy"); // andy3
// //
// ,andy
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
FileOutputStream fos2 = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\NEWvirus.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos2, "MS950");
BufferedWriter bw = new BufferedWriter(osw);
) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
stmt.executeUpdate("DROP TABLE Virus");
boolean rs = stmt.execute(CreateTable);
System.out.println("Database Created");
PreparedStatement pstmt = connection.prepareStatement(InsertData);
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Data Inserted");
} else {
System.out.println("Insert ERROR");
}
ResultSet rs4 = stmt.executeQuery("SELECT Count(*) FROM Virus");
int numberOfData = rs4.getInt(1);
System.out.println(numberOfData);
ResultSet rs3 = stmt.executeQuery(selectQuery);
ResultSetMetaData metaData = rs3.getMetaData();
DatabaseMetaData DmetaData = connection.getMetaData();
String[] types = { "TABLE" };
ResultSet rs5 = DmetaData.getTables(null, null, "Virus", types);
List<String> ColNameList = new ArrayList<String>();
while (rs5.next()) {
String tableName = rs5.getString("TABLE_NAME");
ResultSet columnRs = DmetaData.getColumns(null, null, tableName, null);
while (columnRs.next()) {
String columnName = columnRs.getString("COLUMN_NAME");
ColNameList.add(columnName);
}
System.out.print("|" + ColNameList.get(0) + " |");
System.out.print(ColNameList.get(1) + " |");
System.out.print(ColNameList.get(2) + "|");
System.out.print(ColNameList.get(3) + "|");
System.out.print(ColNameList.get(4) + " |");
System.out.print(ColNameList.get(5) + " |");
System.out.print(ColNameList.get(6) + "  |");
System.out.print(ColNameList.get(7) + "  |");
System.out.print(ColNameList.get(8) + "|");
System.out.print(ColNameList.get(9) + "     |");
System.out.print(ColNameList.get(10) + " |");
System.out.print(ColNameList.get(11) + "|");
System.out.print(ColNameList.get(12) + " |");
System.out.print(ColNameList.get(13) + " |");
System.out.print(ColNameList.get(14) + " |");
System.out.print(ColNameList.get(15) + "");
}
System.out.println();
while (rs3.next()) {
coList1.add(rs3.getString(1));
coList2.add(rs3.getString(2));
coList3.add(rs3.getString(3));
coList4.add(rs3.getString(4));
coList5.add(rs3.getString(5));
coList6.add(rs3.getString(6));
coList7.add(rs3.getString(7));
coList8.add(rs3.getString(8));
coList9.add(rs3.getString(9));
coList10.add(rs3.getString(10));
coList11.add(rs3.getString(11));
coList12.add(rs3.getString(12));
coList13.add(rs3.getString(13));
coList14.add(rs3.getString(14));
coList15.add(rs3.getString(15));
coList16.add(rs3.getString(16));
coList17.add(rs3.getString(17));
}
for (int p = 0; p < 20; p++) { // coList9.size(
System.out.print("|" + coList1.get(p) + "|");
String str2 = coList2.get(p);
if (str2.length() < 3) {
String blank = " ";
String repeated = new String(new char[(3 - str2.length())]).replace("\0", blank);
System.out.print(repeated + coList2.get(p) + "|");
} else {
System.out.print(coList2.get(p) + "|");
}
System.out.print(" " + coList3.get(p) + "|");
System.out.print(coList4.get(p) + "|");
System.out.print(coList5.get(p) + "|");
System.out.print(coList6.get(p) + "|");
System.out.print(coList7.get(p) + "|");
System.out.print(coList8.get(p) + "|");
String str = coList9.get(p);
if (str.length() < 5) {
String blank = " ";
String repeated = new String(new char[(5 - str.length())]).replace("\0", blank);
System.out.print(repeated + coList9.get(p) + "|");
} else {
System.out.print(coList9.get(p) + "|");
}
System.out.print(coList10.get(p) + "|");
System.out.print(coList11.get(p) + "|");
String str12 = coList12.get(p);
if (str12.length() < 5) {
String blank = " ";
String repeated = new String(new char[(6 - str12.length())]).replace("\0", blank);
System.out.print(repeated + coList12.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
String str13 = coList13.get(p);
if (str13.length() < 5) {
String blank = " ";
String repeated = new String(new char[(4 - str13.length())]).replace("\0", blank);
System.out.print(repeated + coList13.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
System.out.print(coList14.get(p) + "|");
System.out.print(coList15.get(p) + "|");
System.out.print(coList16.get(p) + "|");
System.out.print(coList17.get(p) + "|");
System.out.println();
}
rs3.beforeFirst();
StringBuilder builder = new StringBuilder();
builder.append("CaseID").append(",").append("Age").append(",").append("Gender").append(",").append("City")
.append(",").append("SampleDate").append(",").append("VirusType").append(",")
.append("SubType").append(",").append("Locus").append(",").append("Primer").append(",").append("GeneDirection")
.append(",").append("TypingMethod").append(",").append("DNASeq").append(",").append("AminoAcidSeq");
System.out.println(rs3.next());
while (rs3.next()) {
builder.append(System.lineSeparator());
builder.append(rs3.getString(1)).append(",").append(rs3.getString(2)).append(",")
.append(rs3.getString(3)).append(",").append(rs3.getString(5)).append(",")
.append(rs3.getString(7)).append(",").append(rs3.getString(10)).append(",")
.append(rs3.getString(11)).append(",").append(rs3.getString(12)).append(",")
.append(rs3.getString(13)).append(",").append(rs3.getString(14)).append(",")
.append(rs3.getString(15)).append(",").append(rs3.getString(16)).append(",").append(rs3.getString(17)).append(",");
}
bw.write(builder.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
Start refactoring your code in small steps and then iteratively improve your design if needed.
As you have mentioned the algorithmic approach, leveraging that this should be your starting step.
CSV file from url,
then i bulk inserted into sql database,
then call data from SQL server and
display on Java console.
Finally select the column I want to keep
and export as a new CSV file.
Small helper functions for each of these steps.
Read more about SOLID design principles if that helps in improving your solution.

Result Excel Export from Oracle DB

I have written the below Java code, which is executing fine in order to export the results in xlsx file from Oracle DB. But can someone help me to improve the performance of this code by which this below code can extract the result very fast.
Below is the Java Code which I have tried as of now; But it is slow while exporting result as compared to excel export from SQL Developer
public class FilesFromFolder {
private Workbook writeWorkbook;
public void ExportService(DBConnection con) {
writeWorkbook = new XSSFWorkbook();
Sheet desSheet = writeWorkbook.createSheet("Data");
Statement stmt = null;
ResultSet rs = null;
int columnsNumber = 0;
ResultSetMetaData rsmd = null;
FileOutputStream fileOut = null;
Connection cntn = null;
String filePath = "C:\\Users\\Desktop\\OracleExport";
File files = new File(filePath);
File[] file = files.listFiles();
String fileNameWithOutExt = null;
if (file != null) {
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
String tempFilename = file[i].getName();
fileNameWithOutExt = tempFilename.replaceFirst("[.][^.]+$", "");
File fileTemp = file[i];
try {
String fileContent = FileUtils.readFileToString(fileTemp, "UTF8");
// System.out.println(fileContent);
cntn = con.getConnection();
stmt = cntn.createStatement();
rs = stmt.executeQuery(fileContent);
rsmd = rs.getMetaData();
columnsNumber = rsmd.getColumnCount();
Row desRow1 = desSheet.createRow(0);
for (int col = 0; col < columnsNumber; col++) {
Cell newpath = desRow1.createCell(col);
newpath.setCellValue(rsmd.getColumnLabel(col + 1));
}
while (rs.next()) {
System.out.println("Row number -->" + rs.getRow());
Row desRow = desSheet.createRow(rs.getRow());
for (int col = 0; col < columnsNumber; col++) {
Cell newpath = desRow.createCell(col);
newpath.setCellValue(rs.getString(col + 1));
}
String outputFile = "C:\\Users\\Desktop\\OracleExport\\" + fileNameWithOutExt
+ ".xlsx";
fileOut = new FileOutputStream(outputFile);
writeWorkbook.write(fileOut);
}
System.out.println(fileNameWithOutExt + " export complete");
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (fileOut!= null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (cntn != null) {
con.closeConnection();
}
}
}
}
}
}
}

Java - Eclipse to Excel from SQL Query

Getting the results of a SQL query where I want row 5 from every record that is returned.
I would like to export the data to an Excel spreadsheet in rows of thirteen, starting at the second row (I have headers).
My SQL logic is obviously off right now because I'm getting the first result thirteen times in increasing rows and columns, although it is properly starting on the second row and only going out 13 columns. The second result repeats in this fashion, as does each successive result.
I suspect my troubles start at while (rs.next()) {
for (int i = 0; i < 13; i++) {
package process;
import java.util.Scanner;
import java.io.*;
import java.sql.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class Sec_Completions {
public static void main(String[] args) {
Sec_Completions obj_Sec_Completions=new Sec_Completions();
obj_Sec_Completions.Check_Data();
}
public void Check_Data() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the beginning date of completion YYYY/MM/DD");
String doc = scanner.nextLine();
doc = doc + " 00:00";
System.out.println("Date is" + " " + doc);
final String sql = "SELECT DISTINCT wp_grassblade_completions.user_id, wp_grassblade_completions.status, wp_grassblade_completions.content_id, wp_usermeta.meta_key, CASE WHEN meta_value = 'male' THEN 'M' WHEN meta_value = 'female' THEN 'F' WHEN meta_value = 'Louisiana' THEN 'LA' ELSE meta_value END AS '1', wp_usermeta.meta_value, wp_usermeta.user_id, wp_grassblade_completions.timestamp\r\n" +
"FROM wp_grassblade_completions \r\n" +
"INNER JOIN wp_usermeta ON wp_grassblade_completions.user_id = wp_usermeta.user_id\r\n" +
"WHERE wp_grassblade_completions.timestamp >= ? AND meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state', 'mepr_zip_code', 'mepr_home_phone_with_area_code', \r\n" +
" 'mepr_drivers_license_or_id', 'mepr_id_state', 'mepr_LAst_four_of_social_security_number', 'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height', 'mepr_weight') AND content_id IN ('1575, 642, 1580') \r\n" +
"ORDER BY wp_grassblade_completions.timestamp, content_id, wp_usermeta.user_id";
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://wpengine.com:3306/wp_database","user", "passsword");
PreparedStatement ps =null;
ps=connection.prepareStatement(sql);
ps.setString(1, doc);
Statement st = connection.createStatement();
ResultSet rs = ps.executeQuery();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Security");
XSSFRow rowhead = sheet.createRow((short) 0);
int index = 1;
while (rs.next()) {
for (int i = 0; i < 13; i++) {
XSSFRow row = sheet.createRow((short) index);
row.createCell((short) i).setCellValue(rs.getString(5));
index++;
}
}
FileOutputStream fileOut = new FileOutputStream("D://OneDrive//ABSEC//ATC_Reporting//expdata1.xlsx");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();
} catch (Exception e) {
System.out.println(e);
}
Edited, again
Try something like this:
// META_KEY values, in the order that the columns should be. This should be a
// private static final outside of in the class, along with the query's text...
String[] keys = { "mepr_full_name", "mepr_address", "mepr_city", "mepr_state",
"mepr_zip_code", "mepr_home_phone_with_area_code",
"mepr_drivers_license_or_id", "mepr_id_state",
"mepr_LAst_four_of_social_security_number", "mepr_date_of_birth_mmddyyyy",
"mepr_sex_mf", "mepr_height", "mepr_weight" };
// Running thru the ResultSet
short index = 1;
while ( rs.next() )
{
XSSFRow row = sheet.createRow( index );
String key = rs.getString(4); // meta_key
String value = rs.getString( 5 ); // meta_value
for ( short i = 0; i < keys.length; ++i )
{
if ( keys[i].equals( key))
{
// Retrieving cell, creating if not exists
XSSFCell cell = row.getCell( i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK );
// if the cell is used, increment index o get to the next row
if ( cell.getCellTypeEnum() != CellType.BLANK )
++index;
// Set the value
cell.setCellValue( value );
// No need to walk thru the rest of the array...
break;
}
}
}
This only works, tho, if any "next row" does not start with a column that has no value in the previous row...
For this reason you should also add meta_key to the ORDER BY clause...
With some additional cleanup, something like this:
SELECT DISTINCT wpgc.user_id, wpgc.status, wpgc.content_id, wpu.meta_key,
CASE wpu.meta_value WHEN 'male' THEN 'M' WHEN 'female' THEN 'F'
WHEN 'Louisiana' THEN 'LA' ELSE wpu.meta_value END AS '1',
wpu.user_id, wpgc.timestamp
FROM wp_grassblade_completions AS wpgc
JOIN wp_usermeta AS wpu ON wpgc.user_id = wpu.user_id
WHERE wpgc.timestamp >= ?
AND wpu.meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state',
'mepr_zip_code', 'mepr_home_phone_with_area_code',
'mepr_drivers_license_or_id', 'mepr_id_state',
'mepr_LAst_four_of_social_security_number',
'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height',
'mepr_weight')
AND content_id IN ('1575, 642, 1580')
ORDER BY wpgc.timestamp, wpgc.content_id, wpu.user_id, wpu.meta_key

Save As DialogueBox is not working in servlet response.setHeader

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);
}
}

Categories