将DataTable导出到Excel并保存到本地目录

时间:2015-03-08 11:05:10

标签: c# asp.net excel datatable

我有以下功能,它们采用数据表并转换为excel并提示用户下载excel。

我是否知道如何更改功能以便将其保存到本地目录而不是下载?

public static void ExportDataTableToExcel(DataTable table, string name)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();

        string attachment = "attachment; filename=" + name + ".xls";

        context.Response.ClearContent();
        context.Response.AddHeader("content-disposition", attachment);
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.ContentEncoding = System.Text.Encoding.Unicode;
        context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

        string tab = "";

        foreach (DataColumn dc in table.Columns)
        {
            context.Response.Write(tab + dc.ColumnName);
            tab = "\t";
        }

        context.Response.Write("\n");

        int i;
        foreach (DataRow dr in table.Rows)
        {
            tab = "";
            for (i = 0; i < table.Columns.Count; i++)
            {
                context.Response.Write(tab + "=\"" + dr[i].ToString() + "\"");
                tab = "\t";
            }

            context.Response.Write("\n");
        }         

        context.Response.End();
    }

1 个答案:

答案 0 :(得分:0)

找到并实现了功能

public static bool SaveDataTableToExcel(DataTable table, string savePath)
    {
        //open file
        StreamWriter wr = new StreamWriter(savePath, false, Encoding.Unicode);

        try
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                wr.Write(table.Columns[i].ToString().ToUpper() + "\t");
            }

            wr.WriteLine();

            //write rows to excel file
            for (int i = 0; i < (table.Rows.Count); i++)
            {
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (table.Rows[i][j] != null)
                    {
                        wr.Write("=\"" + Convert.ToString(table.Rows[i][j]) + "\"" + "\t");
                    }
                    else
                    {
                        wr.Write("\t");
                    }
                }
                //go to next line
                wr.WriteLine();
            }
            //close file
            wr.Close();
        }
        catch (Exception ex)
        {
            LogError(ex);

            return false;
        }

        return true;
    }