使用c#创建excel XML电子表格的步骤

Eni*_*ate 6 .net c# export-to-excel openxml-sdk

我们有一个要求,比如将数据以Xml格式导出到excel表中,就像创建一个新的XML SpreadSheet一样,我已经按照这个链接创建了excel xml Spreadsheet.在这个链接中,他提到了样本

< ?xml version="1.0"?>
< ?mso-application progid="Excel.Sheet"?>
<workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<documentproperties xmlns="urn:schemas-microsoft-com:office:office">
<author>Author</author>
<lastauthor>LastAuthor</lastauthor>
<created>11-09-2007</created>
<version>12.00</version>
</documentproperties>
<excelworkbook xmlns="urn:schemas-microsoft-com:office:excel">
<protectstructure>False</protectstructure>
<protectwindows>False</protectwindows>
</excelworkbook>
</workbook>
Run Code Online (Sandbox Code Playgroud)

我需要在c#项目中定义这种格式,在上面的代码中我需要获取有关作者和最后作者需要从数据库绑定的信息....

在那个链接中,他没有完全提到创建文档......

如果我想创建一个ExcelXml spread sheet我需要遵循的步骤,我是否需要创建一个将存储在项目中的预定义格式...

我们能够访问开放的XML sdk,但我找到了在excel电子表格中创建xml格式的任何示例解决方案,是否可以做同样的事情open XML SDK,如果有可能你会指出我正确的方向...

任何人都有任何想法和任何解决方案,非常感谢我....

提前谢谢了

Pau*_*hra 1

模板失败请尝试从这里获取以下内容

using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static void CreateSpreadsheetWorkbook(string filepath)
    {
        // Create a spreadsheet document by supplying the filepath.
        // By default, AutoSave = true, Editable = true, and Type = xlsx.

        SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

        // Add a WorkbookPart to the document.
        WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        // Add a WorksheetPart to the WorkbookPart.
        WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());

        // Add Sheets to the Workbook.
        Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

        // Append a new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
        sheets.Append(sheet);

        workbookpart.Workbook.Save();

        // Close the document.
        spreadsheetDocument.Close();
    }

// Called using
CreateSpreadsheetWorkbook("C:\\Test\\Test.xlsx");
Run Code Online (Sandbox Code Playgroud)

编辑:您可以使用以下代码将 xml 转换为 Excel:

Workbook workbook = new Workbook(); 
workbook.LoadFromFile(@"../../Data/test.xml"); 
workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);
Run Code Online (Sandbox Code Playgroud)

如果您想实际创建 Office XML 文档,我不确定如何从 xml 文件自动执行该过程。看看这个以获得一些指导