【问题标题】:Programmatically sort Excel spreadsheets以编程方式对 Excel 电子表格进行排序
【发布时间】:2018-12-28 10:12:07
【问题描述】:

我正在使用 OpenXML 来处理 Excel 文件。

我将 Excel 文件作为内存流发送,对其进行编辑,然后将它们发送回浏览器,以便它们在客户端办公程序中打开。我使用以下代码创建新的电子表格:

public static void InsertWorksheet(string docName)
{

using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
    // Add a blank WorksheetPart.
    WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new Worksheet(new SheetData());

    Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
    string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

    // Get a unique ID for the new worksheet.
    uint sheetId = 1;
    if (sheets.Elements<Sheet>().Count() > 0)
    {
        sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
    }

    // Give the new worksheet a name.
    string sheetName = "Sheet" + sheetId;

    // Append the new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
    sheets.Append(sheet);
} 
}

我的问题是此工作表是在工作簿中的工作表中最后添加的。我希望它是 sheet nr 1。我正在寻找有关如何将新创建的工作表设置为 sheet nr 的提示。 1.

【问题讨论】:

    标签: c# excel sharepoint ms-office openxml


    【解决方案1】:

    也许您调用的不是sheets.Append,而是在开头插入它?有Insert 或Prepend 方法吗?

    【讨论】:

    • 是的,确实如此。感谢您的提示。这成功了:sheets.InsertAt(sheet, 0);
    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2016-09-06
    相关资源
    最近更新 更多