导出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} ============={1}============= {2} {3} {4}",
                        ex.Message,
                        null != ex.InnerException ? ex.InnerException.Message + " " + ex.InnerException.Source + " " + 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("");
                //取得数据表各列标题,各标题之间以 分割,最后一个列标题后加回车符
                for (i = 0; i < DT.Columns.Count - 1; i++)
                {
                    colHeaders += DT.Columns[i].Caption.ToString() + " ";
                }
                colHeaders += DT.Columns[i].Caption.ToString() + " ";
                //向HTTP输出流中写入取得的数据信息
                HttpContext.Current.Response.Write(colHeaders);
                //逐行处理数据
                foreach (DataRow row in myRow)
                {
                    //在当前行中,逐列获得数据,数据之间以 分割,结束时加回车符
                    for (i = 0; i < DT.Columns.Count - 1; i++)
                        ls_item += row[i].ToString() + " ";
                    ls_item += row[i].ToString() + " ";
                    //当前行数据写入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);
        }
    }
}

原文地址:https://www.cnblogs.com/bignine/p/10090900.html