在C#中将网格视图转换为Excel

在C#中将网格视图转换为Excel

问题描述:

请告诉我如何将网格视图导出到不可编辑的Excel工作表.
我已经完成了转换过程,但是我不知道如何使excel工作表不可编辑.

Hi, Please tell me how to export grid view to excel sheet which is not editable.
I have done with the conversion process but i dont know how to make the excel sheet not editable.

尝试 ^ ].

锁定工作表-通过此讨论 [ ^ ].
Try CodeProject Frequently Asked Questions Series 1: The ASP.NET GridView[^].

Locking the sheet - go through this discussion[^].


用于Web应用程序:

for web application :

public static void exportDataTableToExcel(DataTable table, string name)
   {

       try
       {
           HttpContext context = HttpContext.Current;

           context.Response.Clear();
           context.Response.Buffer = true;
           string style = @"<style> .textmode { mso-number-format:\@; } </style>";
           context.Response.Write(style);

           context.Response.Write("<div> ");
           context.Response.Write(Environment.NewLine);
           context.Response.Write("<table>");
           context.Response.Write(Environment.NewLine);
           context.Response.Write("<tr> ");
           context.Response.Write(Environment.NewLine);

           foreach (DataColumn column in table.Columns)
           {
               context.Response.Write("<th style = 'font-weight:bold'>");
               context.Response.Write(column.ColumnName);
               context.Response.Write("</th>");
           }

           context.Response.Write("</tr>");




           foreach (DataRow row in table.Rows)
           {

               context.Response.Write(Environment.NewLine);
               context.Response.Write("<tr> ");
               context.Response.Write(Environment.NewLine);

               for (int i = 0; i < table.Columns.Count; i++)
               {
                   context.Response.Write("<th  style = 'font-weight:Normal' >");
                   context.Response.Write(row[i].ToString());
                   context.Response.Write("</th>");

               }

               context.Response.Write(Environment.NewLine);
               context.Response.Write("</tr> ");
               context.Response.Write(Environment.NewLine);


           }

           context.Response.Write("</table>");
           context.Response.Write(Environment.NewLine);
           context.Response.Write("</div>");
           context.Response.Write(Environment.NewLine);





           context.Response.AddHeader("content-disposition", "attachment;filename=" + name + ".xls");
           context.Response.Charset = "";
           context.Response.ContentType = "application/vnd.ms-excel";

           context.Response.Flush();


           context.Response.End();
       }
       catch (Exception ex)
       {
           throw ex;
       }

   }


您可以尝试
exporttoexcel 工具
You can try
exporttoexcel tool