c#代码导出SQL表数据到Excel每天的基础
本文关键字:每天 Excel 数据 代码 SQL | 更新日期: 2023-09-27 18:13:01
我正在与ASP合作。asp.net MVC 3。我想从SQL Server表导出数据到Excel表,并将其保存在每天的共享路径中。
我如何使用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());
}
有两种设置方法:
- 你可以利用WebAPI来实现和操作执行导出,然后编写控制台应用程序并安排其运行在windows任务调度程序(基本上控制台应用程序将调用WebAPI。
http://yoursite/api/doExport
)。 -
你可以用石英。净
-
最后,你可以像这个例子一样使用cachedItemCallback,但是因为你需要每天运行一次,这种方式可能不适合你。