Rabu, 23 Mei 2012

ASP.NET C# Header Force Download Untuk Report Excel, MHT, HTML, Word

Jika kita ingin membuat Report Excel, MHT, HTML, Word. Bisa dilakukan dengan membuat Dokumen di Microsoft Excel atau Microsoft Word. Kemudian Save As MHT atau HTML. Kemudian ubah ekstensi filenya menjadi ASPX. Setelah itu beri coding ASP.NET C# berikut di atasnya, maka jika dijalankan akan langsung keluar perintah Download, Do You Want to Open or Save this Document. Dan jika dipilih Open maka akan langsung keluar ke Microsoft Office tergantung extensinya *.doc atau *.xls atau *.xlsx atau *.docx bahkan *.mht atau *.htm.

Untuk mengisi data dinamis pada Report tersebut mudah tinggal beri saja coding PHP di dalamnya seperti biasa misal mengambil data dari database dst.

<%@ Page Language="C#" %>
<%@ import Namespace = "System.Data.SqlClient" %>
<%@ import Namespace = "System.Data" %>
<%@ import Namespace = "System.IO" %>
<%
    Response.ClearHeaders();
    Response.AddHeader("Content-Type ", "application/download");
    Response.AddHeader("Content-Disposition", " attachment; filename=laporan.xls");
    Response.AddHeader("Content-Transfer-Encoding", "binary");
    Response.AddHeader("Expires", "0");
    Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    Response.AddHeader("Pragma", "public");

  //public SqlConnection cn;
  //cn = new SqlConnection("Data Source=localhost;Initial Catalog=penjualan;Integrated Security=True");

    
  //cn.Open();
  //SqlCommand cm;
  //cm = new SqlCommand("SELECT * FROM penjualan_muncul WHERE outlet = '" + System.Convert.ToString(Request.Params["outlet"]) + "' AND tanggal >= '" + tgl1 + "' AND tanggal <= '" + tgl2 + "' ORDER BY id_penjualan ASC", cn);
  //SqlDataReader rd;
  //rd = cm.ExecuteReader();
  //while (rd.Read())
  //{
%>

MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----=_NextPart_01CD0915.924C0070"

This document is a Single File Web Page, also known as a Web Archive file.  If you are seeing this message, your browser or editor doesn't support Web Archive files.  Please download a browser that supports Web Archive, such as Windows® Internet Explorer®.

------=_NextPart_01CD0915.924C0070
Content-Location: file:///C:/0A4A9512/barber.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1252"
....