Export xml data to Excel using OpenXML - excel

The file is downloading an xlsx file but when i tried to open the file it is saying file is corrupted. Here is the code i'm trying to use please let me know if any changes has to be done for the following.
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(#"D:\ExcelImport\Input.xml");
xXslt.Load(#"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
Thanks in advance
Vineet Mangal

private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlobj = new XmlDocument();
xmlobj.Load(#"C:\Excel Import\\Input.xml");
XslCompiledTransform xXslt = new XslCompiledTransform();
xXslt.Load(#"C:\ExportToexcel\Data.xslt");
StringWriter sw = new StringWriter();
xXslt.Transform(xmlobj, null, sw);
richTextBox2.Text = sw.ToString();
sw.Close();
XmlDocument Xdoc = new XmlDocument();
Xdoc.LoadXml(sw.ToString());
Xdoc.Save(#"c:\temp\output.xml");
StreamReader sr = File.OpenText(#"c:\temp\output.xml");
string strSheetData = sr.ReadToEnd();
ArrayList DataNode = new ArrayList();
ArrayList FinalXML = new ArrayList();
XmlNodeList DN;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw1 = new StringWriter();
xXslt.Transform(xml, null, sw1);
FinalXML.Add(sw1);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook1 = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook1.AddNewPart<WorksheetPart>();
string sheetId = workbook1.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
**WorbookXML += "<sheet name=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\" r:id=\"" + sheetId.ToString() + "\" />";
AddPartXml(sheet[j], text);**
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook1, WorbookXML);
doc.Close();
}
}
public void AddPartXml(OpenXmlPart part, string xml)
{
**using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}**
}

Related

Converting from HWPFDocument to XWPFDocument or vice versa

I have a Word document, where I have to replace text and save this document in Oracle database, in PDF format. Have someone any idea how to resolve this?
String inputFilename = "/root/GeneratorUmow/web/WEB-INF/umowy/kkb/wniosekozaciag.docx";
try(InputStream is = new FileInputStream(inputFilename)) {
dbd = new DokumentyBlobDAO();
db.setNazwaPliku("Wniosek_o_zaciagniecie.pdf");
db.setTypDokuemntu(876990);
if(du.getTypKlienta() == S_ID_Lead_Partner_Typ_Klienta_KKB) {
POIFSFileSystem fs = null;
fs = new POIFSFileSystem(is);
HWPFDocument doc = new HWPFDocument(fs); //funkcja zamyka inputstream
Range range = doc.getRange();
range.replaceText("my&&nazwa&&firmy", "KAKAOWY SZATAN");
//konwersja na pdf
FileOutputStream fos = new FileOutputStream(pathToDirectory + File.separator + folderName+File.separator + "wniosekzaciagniecie.docx");
doc.write(fos);
String inputChangeFile = pathToDirectory+ File.separator +folderName+File.separator+"wniosekzaciagniecie.docx";
InputStream inputstream = new FileInputStream(inputFilename);
length = inputChangeFile.length();
System.out.println("dlugosc lancucha " + length);
XWPFDocument document = new XWPFDocument(inputstream);
System.out.println("message3");
PdfOptions options = PdfOptions.create();
PdfOptions options = PdfOptions.create().fontEncoding("windows-1250");
System.out.println("message4");
OutputStream out = new FileOutputStream(new File(pathToDirectory+ File.separator +folderName+File.separator+"kakaowyszal.pdf"));
PdfConverter.getInstance().convert(document, out, options);
System.out.println("message5");
}
}
catch( Exception ex){
System.out.println("err" + ex);
return -1;
}

Send DataSet data email via attachment Excel File xls ( Not Creating Excel File ) C#

I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)

Exception on downloading pdf from envelope

When i run this code.The Content is not allowed in prolog is coming.What is wroung in my code.
Here is code.
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class GetEnvelopeDoc
{
// Enter your info:
static String username = "*****";
static String password = "*****";
static String integratorKey = "******";
static String envelopeId = "**************";
static String envelopeUri = "/envelopes/" + envelopeId;
public static void main(String[] args) throws Exception
{
String url = "https://demo.docusign.net/restapi/v2/login_information";
String baseURL = ""; // we will retrieve this
String accountId = ""; // will retrieve
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
int statusValue = conn.getResponseCode(); // side-effect of this call is to fire the request off
if( statusValue != 200 ) // 200 = OK
{
System.out.print("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// we use xPath to get the baseUrl and accountId from the XML response body
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream() ));
StringBuilder responseText = new StringBuilder(); String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
String token1 = "//*[1]/*[local-name()='baseUrl']";
String token2 = "//*[1]/*[local-name()='accountId']";
XPath xPath = XPathFactory.newInstance().newXPath();
baseURL = xPath.evaluate(token1, new InputSource(new StringReader(responseText.toString())));
accountId = xPath.evaluate(token2, new InputSource(new StringReader(responseText.toString())));
//--- display results
System.out.println("baseUrl = " + baseURL + "\naccountId = " + accountId);
//
// STEP 2 - Get Info on Envelope's Document(s)
//
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader(new DataInputStream( conn.getInputStream() ));
System.out.println(isr.toString());
br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
while ( (line = br.readLine()) != null)
response.append(line);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
//--- display results
System.out.println("\nDocument List -->");
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("documentId"))
System.out.print("documentId: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("name"))
System.out.print(", name: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("uri"))
{
docURIs[++cnt] = docNodes.item(j).getTextContent(); // store the uris for later
System.out.print(", uri: " + docURIs[cnt]);
}
}
System.out.println();
}
}
//
// STEP 3 - Download the document(s)
//
for( int i = 0; i < docURIs.length; i++)
{
// append document uri to url for each document
conn = (HttpURLConnection)new URL(baseURL + docURIs[i]).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
statusValue = conn.getResponseCode();
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Grab the document data and write to a local file
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
BufferedWriter out = new BufferedWriter(new FileWriter("document_" + i + ".pdf"));
out.write(response2.toString());
out.close();
}
System.out.println("\nDone downloading document(s)!");
}
}
Your question is not very clear, I don't know what you mean when you say "the content is not allowed in prolog", however it looks like you have some extra characters in your code. Was this part a copy-paste error? You have the > symbols in front of each of these lines.
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request

how to change header column colour in the generated excel

I am exporting data from sql server database to excel in wpf, and I have achieved the function successully. Now I want to change the head column colour in the generated excel. Any ideas? Thanks in advance.
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
// string path = null;
//string myfilename = "Report";
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Name = "Customer List";
//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
//SqlConnection cnn = new SqlConnection(GetConnectionString());
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=ClientLists;Integrated Security=SSPI;";
cnn.Open();
sql = "select FirstName, LastName, City, PostCode, TelephoneNo from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count -1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count -1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
Microsoft.Office.Interop.Excel.Range headerRange1 = xlWorkSheet.get_Range("A1", "A1");
headerRange1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange1.Value = "First Name";
headerRange1.Font.Bold = true;
headerRange1.ColumnWidth = 14;
// headerRange1.Interior.Color = 1;
// headerRange1.Borders.Color = System.Drawing.Color.Red;
Microsoft.Office.Interop.Excel.Range headerRange2 = xlWorkSheet.get_Range("B1", "B1");
headerRange2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange2.Value = "Last Name";
headerRange2.Font.Bold = true;
headerRange2.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange3 = xlWorkSheet.get_Range("C1", "C1");
headerRange3.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange3.Value = "City";
headerRange3.Font.Bold = true;
headerRange3.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange4 = xlWorkSheet.get_Range("D1", "D1");
headerRange4.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange4.Value = "Post Code";
headerRange4.Font.Bold = true;
headerRange4.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange5 = xlWorkSheet.get_Range("E1", "E1");
headerRange5.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange5.Value = "Telephone NO";
headerRange5.Font.Bold = true;
headerRange5.ColumnWidth = 14;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
There is a post that can be found here that says that this is not possible.
However, the c# excel how to change a color of a particular row post on StackOverflow that provides code for changing a row colour... you may be able to adapt it for you purposes.

How to add download option for openwith and saveAs on exporting file to excel in servlet

Hii Guys !!!
I made an application in which i need to export data from database into .excel formate in which i have given hard coded path for generated .excel file to save at particular position on the system.Now as per my requirement I need to give download option for openwith and saveAs from the browser.
Below I am postion my code .Plz guys help me ...will be gratefull.Thanx in advance...
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);
String filename = "d:/".concat(datum1).concat(" ").concat("To").concat(" ").concat(datum2).concat(".xls");
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");
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"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
}
}
You should use Content-Disposition in the response header
Try using this code
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=FileName.xls");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();

Resources