简体   繁体   English

C#代码每天将SQL表数据导出到Excel

[英]C# code to Export SQL Table Data to Excel on daily basis

I'm working with ASP.NET MVC 3. I want to export data from a SQL Server table to an Excel sheet and save it in a share path on a daily basis. 我正在使用ASP.NET MVC3。我想每天将数据从SQL Server表导出到Excel工作表并将其保存在共享路径中。

How can I do this using C# code? 如何使用C#代码执行此操作?

    public static void WriteToCsvFile(this DataTable dataTable, string filePath) 
    {
        var fileContent = new StringBuilder();

        foreach (var col in dataTable.Columns) {
            fileContent.Append(col + ",");
        }

        fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) {

            foreach (var column in dr.ItemArray) {
                fileContent.Append("\"" + column + "\",");
            }

            fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);
        }
        System.IO.File.WriteAllText(filePath, fileContent.ToString());
    }

There is couple ways to setup this: 有几种设置方法:

  1. you could utilize the WebAPI to implement and action that would perform the export, then write a console app and schedule it to run on the windows Task Scheduler( basically the console app will call the WebAPI ie. http://yoursite/api/doExport ). 您可以利用WebAPI实施并执行将执行导出的操作,然后编写控制台应用程序并将其安排在Windows Task Scheduler上运行(基本上,控制台应用程序将调用WebAPI,即http://yoursite/api/doExport )。
  2. You could use Quartz.Net 您可以使用Quartz.Net

  3. Lastly you could utilize the cachedItemCallback like this example , but since you need to run it once a day this way may not work for you. 最后,您可以像本例一样使用cachedItemCallback,但是由于您需要每天运行一次,因此这种方法可能对您不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM