简体   繁体   中英

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.

How can I do this using C# code?

    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 ).
  2. You could use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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