GridView导出Excel

#region ExportExcel
    /// <summary>
    /// 导出Excel
    /// </summary>
    /// <param name="dt">需要导出的数据</param>
    public void ExportExcel(DataTable dt)
    {
        Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook xBook = null;
        Microsoft.Office.Interop.Excel.Worksheet xSheet = null;
        object objOpt = System.Reflection.Missing.Value;
        string strNewFileName = string.Empty;
        try
        {
            string _ProjectID = "AdjustAction" + DateTime.Now.ToString("yyyyMMddhhmmssfff");
            string strFilePath = Server.MapPath(ConfigurationSettings.AppSettings["Adjust_Path"].ToString());
            string strTempFilePath = Server.MapPath(ConfigurationSettings.AppSettings["Adjust_TempFilePath"].ToString());
            strNewFileName = string.Format("{0}\\{1}.xls", strFilePath, _ProjectID);
            string strTemplate = strTempFilePath + "\\TempAdjustAciton.xls";
            if (File.Exists(strTemplate))
            {
                FileInfo fi = new FileInfo(strTemplate);
                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                {
                    fi.Attributes = FileAttributes.Normal;//改变template文件的只读属性
                }
            }
            System.IO.File.Copy(strTemplate, strNewFileName, true);//复制模板

            DateTime createTime = DateTime.Now;
            if (dt != null & dt.Rows.Count != 0)
            {
                int i;
                xBook = xApp.Workbooks.Open(strNewFileName, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt, objOpt);
                xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    xSheet.Cells[i + 2, 1] = Convert.ToString(dt.Rows[i]["SAREA"]);
                    xSheet.Cells[i + 2, 2] = Convert.ToString(dt.Rows[i]["SACTIONNAME"]);
                    xSheet.Cells[i + 2, 3] = dt.Rows[i]["MAXTIME"];
                    xSheet.Cells[i + 2, 4] = dt.Rows[i]["OLDDATA"];
                    xSheet.Cells[i + 2, 5] = dt.Rows[i]["ADJUSTDATA"];
                    xSheet.Cells[i + 2, 6] = dt.Rows[i]["NOWDATA"];
                }
                xBook.Save();
            }
        }
        catch (Exception ex)
        {
            UIHelper.Alert(this.Page, ex.Message.ToString());
        }
        finally
        {
            if (xBook != null)
            {
                xBook.Close(true, objOpt, objOpt);
            }
            if (xApp != null)
            {
                xApp.Quit();
            }
        }
        Response.AppendHeader("Content-Disposition", "attachment;filename=AdjustAction.xls");
        Response.ContentType = "application/ms-excel";
        Response.WriteFile(strNewFileName);
    }
    #endregion

你可能感兴趣的:(GridView)