Asp.net操作Excel

來源:互聯網
上載者:User

標籤:des   style   http   color   os   檔案   資料   io   

using System;using System.IO;using System.Web;using System.Text;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Runtime.InteropServices;using System.Data;/// <summary>///ExportToExcel 的摘要說明/// </summary>public class ExportToExcel{    #region Interop    [DllImport("User32.dll", CharSet = CharSet.Auto)]    public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);    /// <summary>    /// execl 匯出    /// </summary>    /// <remarks>    /// author:zhujt    /// create date:2014-7-24 18:49:54    /// </remarks>    /// <param name="source">資料來源</param>    /// <param name="fileName">檔案名稱</param>    /// <param name="sheetName">工作表名稱</param>    /// <param name="path">路徑</param>     public static void ExportExcel(System.Data.DataTable source, string title, string fileName, string sheetName)    {         // 建立Excel對象        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();        if (excel != null)        {            // 擷取缺少的object類型值            object missing = System.Reflection.Missing.Value;            // 不顯示提示對話方塊            excel.Application.DisplayAlerts = false;            // 建立工作薄對象            Microsoft.Office.Interop.Excel._Workbook wb = excel.Application.Workbooks.Add(1);            // 刪除多餘工作表            if (wb.Sheets.Count > 0) wb.Sheets.Delete();            // 擷取工作表            Microsoft.Office.Interop.Excel._Worksheet sheet = (Microsoft.Office.Interop.Excel._Worksheet)excel.Worksheets.get_Item(1);            // 工作表名稱            sheet.Name = sheetName;            if (sheet != null)            {                 //sheet.Cells.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone;                 // 添加表頭                string[] titles = title.Split('#');                // 列數                int cols = titles.Length;                 for (int i = 0; i < cols; i++)                {                    //設定標題格式                     //sheet.get_Range(sheet.Cells[1, i + 1], sheet.Cells[1, i + 1]).Font.Bold = true;                    //sheet.get_Range(sheet.Cells[5 + i, 1], sheet.Cells[5 + i, 19]).Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);                     sheet.Cells[1, i + 1] = titles[i];                    // 加粗                    sheet.Cells[1, i + 1].Font.Bold = true;                    // 字型大小                    sheet.Cells[1, i + 1].Font.Size = 10;                    // 列寬                    sheet.Cells[1, i + 1].ColumnWidth = titles[i].Length * 2.5;                    // 行高                    sheet.Cells[1, i + 1].RowHeight = 30;                    // 邊框顏色                    sheet.Cells[1, i + 1].Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);                    // 自動換行                    sheet.Cells[1, i + 1].WrapText = true;                    // 水平居右                    sheet.Cells[1, i + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;                    // 垂直置中                    sheet.Cells[1, i + 1].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;                    // NET 4.0                     Microsoft.Office.Interop.Excel.Range range = sheet.Range[sheet.Cells[1, i + 1], sheet.Cells[2, i + 1]];                    range.MergeCells = true;                }                int rows = source.Rows.Count;                Microsoft.Office.Interop.Excel.Range sheetRange = sheet.Range[sheet.Cells[1, 1], sheet.Cells[rows, cols + 1]];                sheetRange.Borders.LineStyle = 1;                sheetRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());                for (int i = 2; i < rows + 2; i++)                {                    for (int j = 2; j < cols + 2; j++)                    {                        sheet.Cells[i, j - 1] = source.Rows[i - 2][j - 2].ToString();                        try                        {                            string a = source.Rows[i - 2][j - 2].ToString();                            string b = source.Rows[i - 1][j - 2].ToString();                            if (a == b)                            {                                sheet.Range[sheet.Cells[i, j - 1], sheet.Cells[i - 1, j - 1]].MergeCells = true;                                sheet.Range[sheet.Cells[i, j - 1], sheet.Cells[i - 1, j - 1]].Value = sheet.Cells[i, j - 1];                            }                        }                        catch { }                    }                }            }            // 擷取案頭路徑            string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);            string path = dir + "\\" + fileName + ".xls";            if (File.Exists(path))                File.Delete(path);            wb.SaveAs(path, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);            // 清除Excel進程            KillExcel(excel);        }        else        {        }    }    /// <summary>    /// 清除Excel進程    /// </summary>    /// <remarks>    /// author:zhujt    /// create date:2014-7-24 19:30:57    /// </remarks>    /// <param name="excel">清除Excel進程</param>    private static void KillExcel(Microsoft.Office.Interop.Excel.Application excel)    {        // 擷取Excel視窗控制代碼         IntPtr hwnd = new IntPtr(excel.Hwnd);        if (hwnd != IntPtr.Zero)        {            // Excel線程ID            int threadID = 0;            GetWindowThreadProcessId(hwnd, out threadID);            // 擷取Excel進程            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(threadID);            // 清除            p.Kill();        }    }    #endregion}/// <summary>/// 匯出輔助類/// </summary>/// <remarks>/// author:zhujt/// create date:2014-7-24 19:37:32/// </remarks>public class UserExport{    private System.Data.DataTable _source;    /// <summary>    /// 資料來源    /// </summary>    public System.Data.DataTable source    {        get { return _source; }        set { _source = value; }    }    private string _title;    /// <summary>    /// 表頭名稱 以#分割    /// </summary>    public string title    {        get { return _title; }        set { _title = value; }    }    private string _fileName;    /// <summary>    /// 檔案名稱    /// </summary>    public string fileName    {        get { return _fileName; }        set { _fileName = value; }    }    private string _sheetName;    /// <summary>    /// 工作薄名稱    /// </summary>    public string sheetName    {        get { return _sheetName; }        set { _sheetName = value; }    }    /// <summary>    /// 資料資料匯出    /// </summary>    public void ExportExcel()    {        ExportToExcel.ExportExcel(this._source, this._title, this._fileName, this._sheetName);    }}

ExportExcel.rar

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.