使用C#删除excel中的空行

我想在程序执行结束时删除空行 。 详细我插入一些结果后计算使用C#在预定义的Excel表单。 最后,我需要以编程方式删除/删除空行。 有没有人能提出解决scheme? 我的代码很小,所以我无法在这里包括。 为了您的理解,我给出了一些excel的input和输出视图。 在下面的输出Excel中,具有空行的行DE我想在不提及范围的情况下以编程方式删除。

inputExcel /预定义的Excel文件

A 1 2 3 4 B C D E 

输出Excel

 A 1 2 3 4 B ABc cde nAC 123 C cdf fed x2 123 D E 

你可以使用Range对象来做到这一点。 我在这里假设你正在使用Excel互操作。

假设你打开了你的书,然后设置范围然后删除它应该看起来像这样

 ApplicationClass excel = new ApplicationClass(); //... Microsoft.Office.Interop.Excel.Range cel = (Range)excel.Cells[rowIndex, columnIndex]; cel.Delete(); 

你也可以尝试使用:

 for(int i = 1; i <=20; i++) { excelRange = (Excel.Range)excelWorkSheet.Cells[i, 1]; if (!string.IsNullOrEmpty(excelRange.Text.ToString())) { ((Range)excelWorkSheet.Rows[i]).Delete(excelRange); } } 

看看下面的链接

https://social.msdn.microsoft.com/Forums/office/en-US/469fdf10-35cc-46b2-a875-7b974deb5659/how-to-delete-all-empty-rows-from-a-excel-sheet-使用-microsoftofficeinteropexcel?论坛= exceldev

https://stackoverflow.com/a/9952004/4373895这里“东西”是你的空值&#x3002;

希望这可以帮助。

您可以使用以下代码删除Excel文件中的空行

  xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook excelWorkbook = xlApp.Workbooks.Open(fileName); Microsoft.Office.Interop.Excel._Worksheet sheet = excelWorkbook.Sheets[1]; var LastRow = sheet.UsedRange.Rows.Count; LastRow = LastRow + sheet.UsedRange.Row - 1; for (int i = 1; i <= LastRow; i++) { if (application.WorksheetFunction.CountA(sheet.Rows[i]) == 0) (sheet.Rows[i] as Microsoft.Office.Interop.Excel.Range).Delete(); } 

下面的代码完美地工作,并为指定的行号和列号创build一个新的空白行:

 Excel.Range rng = (Excel.Range)xlWorkSheet1.Cells[RowNumber, ColumnNumber]; Excel.Range Row1 = rng.EntireRow; Row1.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false); 

从Excel工作表中删除空行和列的扩展方法。

 /// <summary> /// Deletes empty rows and columns from the end of the given worksheet /// </summary> public static void Trim(this Excel.Worksheet worksheet) { worksheet.TrimColumns(); worksheet.TrimRows(); } /// <summary> /// Deletes empty rows from the end of the given worksheet /// </summary> public static void TrimRows(this Excel.Worksheet worksheet) { Excel.Range range = worksheet.UsedRange; while(worksheet.Application.WorksheetFunction.CountA(range.Rows[range.Rows.Count]) == 0) (range.Rows[range.Rows.Count] as Excel.Range).Delete(); } /// <summary> /// Deletes empty columns from the end of the given worksheet /// </summary> public static void TrimColumns(this Excel.Worksheet worksheet) { Excel.Range range = worksheet.UsedRange; while(worksheet.Application.WorksheetFunction.CountA(range.Columns[range.Columns.Count]) == 0) (range.Columns[range.Columns.Count] as Excel.Range).Delete(); }