c# 使用 Microsoft Interop 对 Excel 中的行进行排序

c# Sorting Rows in Excel using Microsoft Interop

我一直在尝试根据第一列(即日期)对范围进行排序。但是当我 运行 我的代码似乎没有发生任何事情。文件没有变化。以下是我的代码。

Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        String file = @"C:\Book1.xlsx";
        xlWorkBook = xlApp.Workbooks.Open(file);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
       
        Excel.Range rng = xlWorkSheet.get_Range("B16", "I38");

        rng.Sort(rng.Columns[1, Type.Missing], Excel.XlSortOrder.xlDescending,
                        Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending,
                        Type.Missing, Excel.XlSortOrder.xlAscending,
                        Excel.XlYesNoGuess.xlYes, Type.Missing, Type.Missing,
                        Excel.XlSortOrientation.xlSortColumns,
                        Excel.XlSortMethod.xlPinYin,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal);
        
       
        xlWorkBook.Close(true, misValue, misValue);

因为您将 null 值设置为 rngsort 变量。

如果有人正在寻找解决方案。

Excel.Application xlApp = new Excel.Application();
        # setup constants, workbook, sheet, etc.
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        String file = @"C:\Book1.xlsx";
        xlWorkBook = xlApp.Workbooks.Open(file);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        # identify the last row from the used range of the column of interest (column B in this case)
        Excel.Range UsedRange = xlWorkSheet.UsedRange.Columns["B:B"];
        int lastRow = UsedRange.Row + UsedRange.Rows.Count - 1;
        
        # get range of interest...B15:I<last row>
        Excel.Range rng = xlWorkSheet.get_Range("B15", "I" + lastRow);

        # finally, sort the rows of the range of interest according to the original criteria
        rng.Sort(rng.Rows, Excel.XlSortOrder.xlAscending,
                        Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending,
                        Type.Missing, Excel.XlSortOrder.xlAscending,
                        Excel.XlYesNoGuess.xlYes, Type.Missing, Type.Missing,
                        Excel.XlSortOrientation.xlSortColumns,
                        Excel.XlSortMethod.xlPinYin,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal);
        rng = null;