如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?


当前回答

你可能想看看GemBox.Spresheet。

他们有一个免费版本,具有所有功能,但如果符合您的需要,则限制为每张150行,每张工作簿5页。

我还不需要自己使用它,但看起来很有趣。

其他回答

也可以使用Aspose这样的第三方库。

此库的优点是它不需要在您的计算机上安装Excel,这在您的情况下是理想的。

下面是使用LINQ to XML完成此操作的方法,并提供示例代码:

用LINQ to XML快速导入和导出Excel数据

它有点复杂,因为您必须导入名称空间等等,但它确实可以避免任何外部依赖。

(当然,它是VB.NET,而不是C#,但您可以始终在自己的项目中隔离VB.NET内容,以使用XML文字,并使用C#执行其他所有操作。)

Syncfusion Essential XlsIO可以做到这一点。它对Microsoft office没有依赖性,并且对不同的平台也有特定的支持。

ASP.NET网站ASP.NET MVC超临界压力Xamarin公司WPF和Windows窗体Windows服务和基于批处理的操作

代码示例:

//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);

如果您符合资格(收入低于100万美元),可通过社区许可计划免费获得整套控件。注:我为Syncfusion工作。

您可以使用此库创建格式良好的Excel文件:http://officehelper.codeplex.com/documentation参见以下示例:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

示例如下:

private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}

前段时间,我在NPOI上创建了一个DLL。使用它非常简单:

IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople); 
MemoryStream memory = engine.Export();

你可以在这里阅读更多。

顺便说一句,它是100%开源的。随时使用、编辑和共享;)