如何在 C# 中对工作表位置重新排序

本文关键字:新排序 排序 位置 工作 | 更新日期: 2023-09-27 18:31:52

我正在尝试重新排列我在 C# 中创建的 Excel 工作簿中工作表的顺序; 我希望产品工作表在工作簿中出现第一个。 我尝试过"移动",但它没有被识别。 任何想法都非常感谢!

public static bool ExportReportToExcel(DataSet ds, string fileName, 
    DateTime startDate, DateTime endDate)
{
    bool isSuccessful = false;
    try
    {
        Console.WriteLine("Creating Excel File at {0}", DateTime.Now.ToString());
        // Save file after processing to local folder (in case 
        // network location is blocked, we will still have the file)
        if (File.Exists(fileName)) { File.Delete(fileName); }
        // create new workbook for the new source
        XLWorkbook wb = new XLWorkbook();
        // Set default font for workbook
        wb.Style.Font.FontName = "Arial";
        wb.Style.Font.FontSize = 8;
        List<Definition> definitions = GetDefinitions(ds.Tables[1]);
        IXLWorksheet ws = wb.AddWorksheet("Products");
        WriteHeaders(ws, ds, startDate, endDate, definitions);
        WriteTotals(ws, startDate, endDate);
        WriteDetails(ws, ds, startDate, endDate);
        IXLWorksheet defWS = Tools.AddDefinitionsWorksheet(wb, definitions, 
            "Product Report", 4, 60, false);
        WriteSourcesToDefinitions(defWS, ds);
        // save file
        wb.SaveAs(fileName);
        isSuccessful = true;                
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message + "'n" + ex.StackTrace);
        string logFileName = ConfigurationManager.AppSettings["ErrorLogFile"];
        Tools.LogToFile(logFileName, "ProductRpt", "Exception: " + ex.Message + 
            "'n" + ex.StackTrace);
    }
    return isSuccessful;
}

如何在 C# 中对工作表位置重新排序

您需要使用 Position 属性。尝试添加

ws.Position = 1;

以下是参考资料: https://closedxml.codeplex.com/wikipage?title=Organizing%20Sheets&referringTitle=Documentation

看看XLWorkbook类中的这个函数重载:

    public IXLWorksheet AddWorksheet(String sheetName, Int32 position)
    {
        return Worksheets.Add(sheetName, position);
    }

如您所见,您可以将所需的位置传递给此函数