導出excel圖片報表
ExcelExportHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.IO;
using System.Data.OleDb;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Net;
using System.Runtime.InteropServices;
namespace Web.WebCommon
{
/// <summary>
/// EXCEL根據模板導出
/// 2013-03-20
/// HXL
/// </summary>
public class ExcelExportHelper : System.Web.UI.Page
{
private Excel.Application excelApp = null;//
private Excel.Workbooks workbooks = null;//
private Excel.Workbook workbook = null;//
private Excel.Sheets sheets = null;//
private Excel.Range range = null;
private string templatePath = "";
public Excel.Worksheet worksheet = null;//
public string filePath = "";
/// <summary>
/// 實例化一個EXCEL進程
/// </summary>
/// <param name="excelTemplatePath">模板路徑</param>
/// <param name="outputFileDir">輸出目錄,默認為EXCEL臨時目錄</param>
public ExcelExportHelper(string excelTemplatePath, string outputFileDir = "BBM/Upload/")
{
try
{
// worksheet.Outline.
this.templatePath = excelTemplatePath;
if (!File.Exists(templatePath))
{
throw new Exception("沒找到excel模板!");
}
string name = Guid.NewGuid().ToString().Replace("-", "");
string webPath = string.Format(HttpContext.Current.Server.MapPath("~/")+outputFileDir + "{0}.xls", name);
filePath = (webPath);
excelApp = new Excel.Application();
workbooks = excelApp.Workbooks;
workbook = workbooks.Add(templatePath);
sheets = workbook.Worksheets;
worksheet = sheets.get_Item(1);
}
catch (Exception ex)
{
using (FileStream fs = new FileStream(Server.MapPath("~/error.txt"), FileMode.OpenOrCreate))
{
byte[] buffer = System.Text.Encoding.Default.GetBytes(string.Format(
"{0}\r\n============={1}=============\r\n{2}\r\n{3}\r\n{4}",
ex.Message,
null != ex.InnerException ? ex.InnerException.Message + "\r\n" + ex.InnerException.Source + "\r\n" + ex.InnerException.StackTrace : "",
ex.Source,
ex.StackTrace,
ex.TargetSite));
fs.Write(buffer, 0, buffer.Length);
}
throw ex;
}
}
/// <summary>
/// 保存EXCEL
/// </summary>
public void Save()
{
try
{
//另存為
worksheet.SaveAs(
filePath,
56, //Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value,
Missing.Value,
Missing.Value
);
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Workbooks.Close();
excelApp.Quit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(!killexcel(excelApp)){
sheets = null;
workbooks = null;
excelApp = null;
GC.Collect();
using (FileStream fs = new FileStream(Server.MapPath("~/error1.txt"), FileMode.OpenOrCreate))
{
byte[] buffer = System.Text.Encoding.Default.GetBytes("1111");
fs.Write(buffer, 0, buffer.Length);
}
}
}
}
/// <summary>
/// 寫入List數據
/// </summary>
/// <param name="list"></param>
public void WriteList(IList list, int startRowIndex = 2, int startColumnIndex = 1)
{
if (list != null && list.Count > 0)
{
//循環寫內容
for (int i = 0; i < list.Count; i++)
{
}
}
}
/// <summary>
/// 插行(在指定WorkSheet指定行上面插入指定數量行)
/// </summary>
/// <param name="sheetIndex"></param>
/// <param name="rowIndex"></param>
/// <param name="count"></param>
public void InsertRows(int rowIndex, int count = 1, int sheetIndex = 1)
{
try
{
worksheet = (Excel.Worksheet)workbook.Worksheets[sheetIndex];
range = (Excel.Range)worksheet.Rows[rowIndex, Missing.Value];
for (int i = 0; i < count; i++)
{
range.Insert(Excel.XlDirection.xlDown);
}
}
catch (Exception e)
{
throw e;
}
}
// 強行關閉指定的Excel進程
[DllImport("User32.dll",EntryPoint = "GetWindowThreadProcessId")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int Processid);
public bool killexcel(Excel.Application theApp)
{
int iId = 0;
IntPtr intptr = new IntPtr(theApp.Hwnd);
System.Diagnostics.Process p = null;
try
{
GetWindowThreadProcessId(intptr, out iId);
if (iId > 0)
{
p = System.Diagnostics.Process.GetProcessById(iId);
if (p != null)
{
if (p.Id > 0)
{
p.Kill();
p.Dispose();
return true;
}
}
}
}
catch
{
}
return false;
}
}
}
Helper.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
namespace Web.WebCommon
{
public class Helper:System.Web.UI.Page
{
public static void ToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
public static void ToExcel(System.Web.UI.Control ctl, string fileName)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName) + ".xls");
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
public static bool ToExcel(string strFileName, System.Data.DataTable DT)
{
try
{
//清除Response緩存內容
HttpContext.Current.Response.Clear();
//緩存輸出,並在完成整個響應之後將其發送
HttpContext.Current.Response.Buffer = true;
//strFileName指定輸出文件的名稱,註意其擴展名和指定文件類型相符,可以為:.doc .xls .txt .htm
strFileName = strFileName + ".xls";
//設置輸出流的HTPP字符集,確定字符的編碼格式
//HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//下面這行很重要, attachment 參數表示作為附件下載,您可以改成 online在線打開
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
//Response.ContentType指定文件類型.可以為application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他瀏覽器可直接支持文檔
HttpContext.Current.Response.ContentType = "application/ms-excel";
string colHeaders = "", ls_item = "";
int i = 0;
//定義表對象與行對像,同時用DataSet對其值進行初始化
DataRow[] myRow = DT.Select("");
//取得數據表各列標題,各標題之間以\t分割,最後一個列標題後加回車符
for (i = 0; i < DT.Columns.Count - 1; i++)
{
colHeaders += DT.Columns[i].Caption.ToString() + "\t";
}
colHeaders += DT.Columns[i].Caption.ToString() + "\n";
//向HTTP輸出流中寫入取得的數據信息
HttpContext.Current.Response.Write(colHeaders);
//逐行處理數據
foreach (DataRow row in myRow)
{
//在當前行中,逐列獲得數據,數據之間以\t分割,結束時加回車符\n
for (i = 0; i < DT.Columns.Count - 1; i++)
ls_item += row[i].ToString() + "\t";
ls_item += row[i].ToString() + "\n";
//當前行數據寫入HTTP輸出流,並且置空ls_item以便下行數據
HttpContext.Current.Response.Write(ls_item);
ls_item = "";
}
//寫緩沖區中的數據到HTTP頭文件中
HttpContext.Current.Response.End();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Excel文件打開/下載
/// </summary>
/// <param name="fileName">Excel文件名稱</param>
/// <param name="fileUrl">文件路徑</param>
public static void OpenExcel(string fileName,string fileUrl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName) + ".xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
HttpContext.Current.Response.WriteFile(fileUrl);
HttpContext.Current.Response.Flush();
File.Delete(fileUrl);
HttpContext.Current.Response.End();
}
}
}
Query2.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL.BBM;
using Web.COM;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
using Web.WebCommon;
namespace Web.BBM.Query
{
public partial class Query2 : BasePage
{
protected string text = string.Empty;
protected int year = 0;
private DataTable dt = null;
protected void Page_Load(object sender, EventArgs e)
{
int.TryParse(Request.QueryString["year"], out year);
if (year == 0)
year = DateTime.Now.Year;
if (!IsPostBack)
Query_2();
}
void Query_2()
{
dt = new BBMProjectInfoManager().Query_2(year);
if (dt != null && dt.Rows.Count > 0)
{
string split = "";
foreach (DataRow row in dt.Rows)
{
text += split + "{name: ‘" + row["a1"] + "年‘,data: [" + row["a2"] + "," + row["a3"] +
"," + row["a4"] + "," + row["a5"] +
"," + row["a6"] + "," + row["a7"] + "," + row["a8"] +
"," + row["a9"] + "," + row["a10"] +
"," + row["a11"] + "," + row["a12"] + "," + row["a13"] + "," + row["a14"] + "]}";
split = ",";
}
}
rptData.DataSource = dt;
rptData.DataBind();
}
/// <summary>
/// excel導出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtnExcel_Click(object sender, EventArgs e)
{
dt = new BBMProjectInfoManager().Query_2(year);
if (dt == null || dt.Rows.Count <= 0) return;
//實例化EXCEL
var excel = new ExcelExportHelper(HttpContext.Current.Server.MapPath("~/")+"BBM/ExcelTemplates/文件名.xls");
//第一列默認為表頭
excel.worksheet.Cells[1, 1] = year - 2 + "年 - " + year + "年 文件名";
int startRow = 3;
//循環寫內容
for (int i = 0; i < dt.Rows.Count; i++)
{
excel.worksheet.Cells[i + startRow, 1] = dt.Rows[i]["a1"] + "年";
excel.worksheet.Cells[i + startRow, 2] = dt.Rows[i]["a2"];
excel.worksheet.Cells[i + startRow, 3] = dt.Rows[i]["a3"];
excel.worksheet.Cells[i + startRow, 4] = dt.Rows[i]["a4"];
excel.worksheet.Cells[i + startRow, 5] = dt.Rows[i]["a5"];
excel.worksheet.Cells[i + startRow, 6] = dt.Rows[i]["a6"];
excel.worksheet.Cells[i + startRow, 7] = dt.Rows[i]["a7"];
excel.worksheet.Cells[i + startRow, 8] = dt.Rows[i]["a8"];
excel.worksheet.Cells[i + startRow, 9] = dt.Rows[i]["a9"];
excel.worksheet.Cells[i + startRow, 10] = dt.Rows[i]["a10"];
excel.worksheet.Cells[i + startRow, 11] = dt.Rows[i]["a11"];
excel.worksheet.Cells[i + startRow, 12] = dt.Rows[i]["a12"];
excel.worksheet.Cells[i + startRow, 13] = dt.Rows[i]["a13"];
excel.worksheet.Cells[i + startRow, 14] = dt.Rows[i]["a14"];
//插入行
excel.InsertRows(i + startRow + 1);
}
// ActiveSheet.ChartObjects("圖x").Activate
//‘ActiveChart.SeriesCollection.
//‘ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$C$3")
//‘ActiveChart.SetSourceData Source:=Range("B30:G31")
//ActiveChart.SetSourceData Source:=Range("C30:C32,E30:E32,G30:G32") ‘ca.Chart.SetSourceData
//ActiveChart.SeriesCollection(1).Name = "2012" ‘ca.Chart.SeriesCollection(1).Name
//ActiveChart.SeriesCollection(2).Name = "2011"
//ActiveChart.SeriesCollection(3).Name = "2010"
//‘ActiveChart.SeriesCollection = Range("A30:A32")
//ActiveChart.SeriesCollection(1).XValues = Range("B28,D28,F28") ‘ca.Chart.SeriesCollection(1).XValues
//‘ActiveChart.SeriesCollection(2).XValues = Range("D28")
Excel.ChartObject ca = (Excel.ChartObject)excel.worksheet.ChartObjects("圖形1");
string temp = "B" + startRow + ":B" + (dt.Rows.Count + startRow - 1) + ",C" + startRow + ":C" + (dt.Rows.Count + startRow - 1) + ",D" + startRow + ":D" + (dt.Rows.Count + startRow - 1) + ",E" + startRow + ":E" + (dt.Rows.Count + startRow - 1) + ",F" + startRow + ":F" + (dt.Rows.Count + startRow - 1) + ",G" + startRow + ":G" + (dt.Rows.Count + startRow - 1) + ",H" + startRow + ":H" + (dt.Rows.Count + startRow - 1) + ",I" + startRow + ":I" + (dt.Rows.Count + startRow - 1) + ",J" + startRow + ":J" + (dt.Rows.Count + startRow - 1) + ",K" + startRow + ":K" + (dt.Rows.Count + startRow - 1) + ",L" + startRow + ":L" + (dt.Rows.Count + startRow - 1) + ",M" + startRow + ":M" + (dt.Rows.Count + startRow - 1) + ",N" + startRow + ":N" + (dt.Rows.Count + startRow - 1);
//excel.worksheet.get_Range("C" + startRow + ":C" + (dt.Rows.Count + startRow - 1));
ca.Chart.SetSourceData(excel.worksheet.Range[temp], Excel.XlRowCol.xlRows);
ca.Chart.SeriesCollection(1).XValues = excel.worksheet.get_Range("B2,C2,D2,E2,F2,G2,H2,I2,J2,K2,L2,M2,N2");
ca.Chart.SeriesCollection(1).Name = year - 2 + "年";
ca.Chart.SeriesCollection(2).Name = year - 1 + "年";
ca.Chart.SeriesCollection(3).Name = year + "年";
//保存輸出
excel.Save();
string file = excel.filePath;
Helper.OpenExcel("文件名", file);
}
}
}
導出excel圖片報表