如何从C#保存到Excel?

BOWorkerDetail oBOWorkerDetail = new BOWorkerDetail(); WorkerDetails oWorkerDetails = new WorkerDetails(); oWorkerDetails = oBOWorkerDetail.Gets(); 

oWorkerdetails是所有工人的集合。 我需要在Excel中保存这个值。 怎么做 ? 任何人都可以帮忙吗?我在C#窗口平台vs05上工作。

你应该看看这个http://www.connectionstrings.com/excel ,在那里你可以find一些ODBC引擎的连接string。 一个例子是:

 OdbcConnection connection = new OdbcConnection(@"Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=" + xlsFilePath + "; ReadOnly=False; DefaultDir=" + xlsDir + ";"); 

(您应该在工作站上安装Microsoft Excel)

那么你可以像这样创build一个IDbCommand:IDbCommand command = connection.CreateCommand();

您可以像使用任何sql命令一样使用此命令:DataTable中每个DataRow的“CREATE TABLE”,“INSET INTO”。

希望这可以帮助…

我的build议是使用本地库,避免Interop。 看看Aspose.Cells

以下是使用Office 2008和Office Excel Interop的Visual Studio工具向新Excel文件写入列表>的示例:

 using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Office.Interop.Excel; namespace Project1 { public class ExportExcel { public void Export(string fileName, List<List<string>> data) { _Application excel = null; _Workbook wb = null; try { excel = new ApplicationClass { Visible = false }; // new excel application (not visible) wb = excel.Workbooks.Add(Missing.Value); // new excel file var sh = ((_Worksheet)wb.ActiveSheet); // current sheet for (var i = 0; i < data.Count; i++) { var listMaster = data[i]; for (var j = 0; j < listMaster.Count; j++) { sh.get_Range(sh.Cells[j + 1, i + 1], sh.Cells[j + 1, i + 1]).Value2 = listMaster[j]; // get_Range(start, end) where start, end is in R1C1 notation } } } finally { if (wb != null) { wb.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } if (excel != null) { excel.Quit(); } GC.Collect(); } } } } 

VSTO需要在客户机上安装Excel

如果在运行代码的计算机上没有安装Excel,则可以导出为XML或CSV(逗号分隔值)文件,然后在稍后将其导入到Excel中。

如果你使用XML,你也可以导出模式。

正如BarneyHDog在评论中指出的那样,Excel可以根据数据types来判断数据是否令人讨厌。 所以,如果你走这条路线,请检查你的输出是否正确处理。

一个非常简单的方法是使用filehelpers库

http://filehelpers.sourceforge.net/

那里有大量的例子。

图书馆真的很可靠,我用了很多次。 希望能帮助到你