转(学习中)

今天先总结导出为Excel的几种方法:

(一)直接从Gridview中导出数据到Excel:

protected void btnExport_Click(object sender, EventArgs e)
    {

string sql="";
        DataTable MyTable = DB.getdatetable(sql);
        grvExport.DataSource = MyTable;
        grvExport.DataBind();

Response.Clear();
        Response.Charset = "GB2312";
        Response.Write("<meta http-equiv=Content-Type  content=text/html;charset=GB2312>");

Response.AddHeader("content-disposition", "attachment; filename=WWInvReport.xls");
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

grvExport.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();

hw.Dispose();
        tw.Dispose();

MyTable.Dispose();
        adp.Dispose();
        cnn.Dispose();
        GC.Collect();
    }


    public override void VerifyRenderingInServerForm(Control control)
    {

}

 

下面的过载函数一定要有,否则会出错;注意GridView若是分页或者排序的先将其设置为false;

若不希望有列的数字转化为科学计数法在DataBound中设置

if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");            
        }

(二)用拼写HTML的方法直接输出:

public static void DownLoad_SQLtoExcel_2(Page page, DataView dv, string fileName)
    {
        StringBuilder sb = new StringBuilder();
        page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        sb.Append("<html><head>");
        sb.Append("<meta http-equiv=Content-Type content="text/html; charset=utf-8"></head><body><table border=1 style='font-weight:bold;font-size:12px;font-family:Times New Roman;'>");
        sb.Append("<tr style='color:#FFFFFF;height: 22px;vertical-align:middle;'>");
        //第一行表頭

for (int i = 0; i < dv.Table.Columns.Count; i++)
        {
            sb.Append("<td align='center' style='background-color:#999999;'>")

.Append("&nbsp;" + dv.Table.Columns[i].ToString())

.Append("</td>");
        }
        sb.Append("</tr>");


        for (int i = 0; i < dv.Count; i++)
        {
            sb.Append("<tr style='color:#000000;text-decoration:none;background-color:#FFFFFF;line-height:22px;text-align:center;'>");
            //固定位置單元值

for (int j = 0; j < dv.Table.Columns.Count; j++)
            {
                string cells = dv.Table.Rows[i][j].ToString();

sb.Append("<td width='100px' align='center' style='vnd.ms-excel.numberformat:@;'>" + cells + "</td>");
            }
            sb.Append("</tr>");
        }
        sb.Append("</table></body></html>");
        page.Response.Write(sb.ToString());
        page.Response.End();

(三)分Sheet导出

public static void Excel(DataSet ds, string file_path_name, string file_name)
    {
        //定义动态数组,以便存放dataset中每个表的记录数
        long[] rows = new long[ds.Tables.Count];
        string saveFileName = file_path_name;

Application xlApp = new Excel.ApplicationClass();
               _Workbook workbook=xlApp.Workbooks.Add(true);

_Worksheet worksheet =null;   //取得sheet1

//查看本机是否装有OFFICE软件
        if (xlApp == null)
        {
            return;
        }

//tc是table_count,用来遍历每个表
        for (int tc = 0; tc < ds.Tables.Count; tc++)
        {
            object missing1 = System.Reflection.Missing.Value;            
            worksheet = (Excel.Worksheet)workbook.Worksheets.Add(missing1, missing1, missing1, missing1);//添加一个sheet
            worksheet.Name = ds.Tables[tc].TableName; //将DataSet表名来作为输出Excel中Sheet的名字
            rows[tc] = ds.Tables[tc].Rows.Count;

//定义动态数姐存放所有需要汇出的数据
            string[,] datas = new string[ds.Tables[tc].Rows.Count + 1, ds.Tables[tc].Columns.Count];

for (int i = 0; i < ds.Tables[tc].Columns.Count; i++) //写入标题
            {
                datas[0, i] = ds.Tables[tc].Columns[i].Caption;
            }
            //标题的记录区域range_title
            Excel.Range range_title = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, ds.Tables[tc].Columns.Count]);
            range_title.Interior.ColorIndex = 15;   //15代表灰色
            range_title.Font.Bold = true;
            range_title.Font.Size = 9;

//r用来记录table的行数,j用来记录table的列数
            int r = 0;
            for (r = 0; r < ds.Tables[tc].Rows.Count; r++)
            {
                for (int j = 0; j < ds.Tables[tc].Columns.Count; j++)
                {
                    if (ds.Tables[tc].Columns[j].DataType == typeof(string) || ds.Tables[tc].Columns[j].DataType == typeof(int) || ds.Tables[tc].Columns[j].DataType == typeof(Decimal) || ds.Tables[tc].Columns[j].DataType == typeof(DateTime))
                    {
                        //依次取每行每列的数据
                        object obj = ds.Tables[tc].Rows[r][ds.Tables[tc].Columns[j].ColumnName];
                        datas[r + 1, j] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                    }
                }
            }
            //定义整个区域包括标题和数据
            Excel.Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[ds.Tables[tc].Rows.Count + 1, ds.Tables[tc].Columns.Count]);
            fchR.Value2 = datas;
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
            //标题的记录区域range_data
            Excel.Range range_data = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[ds.Tables[tc].Rows.Count + 1, ds.Tables[tc].Columns.Count]);
            range_data.Font.Size = 9;
            range_data.RowHeight = 14.25;
            range_data.Borders.LineStyle = 1;
            range_data.HorizontalAlignment = 1;
            //--合併單元格的操作--
            //數組操作從0開始,ExcelCells從1開始

int n = 2; //Excel從第2行開始,因為第一行是標題
            for (int m = 2; m <= ds.Tables[tc].Rows.Count + 1; m++)
            {
                if (m <ds.Tables[tc].Rows.Count+1)
                {
                    if (ds.Tables[tc].Rows[m - 2][0].ToString() == ds.Tables[tc].Rows[m - 1][0].ToString())//DataTable是從第0行開始
                    {
                        xlApp.Cells[m + 1, 1] = "";
                    }
                    else
                    {
                        worksheet.get_Range((Excel.Range)worksheet.Cells[n, 1], (Excel.Range)worksheet.Cells[m, 1]).Merge(0);//合并单元格
                        n = m + 1;
                    }
                }
                else
                {
                    worksheet.get_Range((Excel.Range)worksheet.Cells[n, 1], (Excel.Range)worksheet.Cells[m, 1]).Merge(0);
                }

}

}
                       workbook.Saved = true;
                workbook.SaveCopyAs(saveFileName);
                workbook.Close(false, null, null);                
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.WriteFile(file_path_name);
                response.Charset = "utf-8";
                response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                response.ContentType = "application/ms-excel";
                string httpHeader = "attachment;filename=" + file_name + ".xls";
                response.AppendHeader("Content-Disposition", httpHeader);
                response.Flush();
                System.IO.File.Delete(saveFileName);//删除临时文件                
                       xlApp.Quit();
               GC.Collect();//强行销毁
        response.End();
    }
这种方法用的时候,需要在服务器上设置元件服务的权限,另外一定要有workbook.Close(false, null, null);                这句,否则的话每次会在服务器上开启一个Excel进程,多次之后就会报错;

原文地址:https://www.cnblogs.com/qietingfengying/p/2860501.html