追加到excel,但两次发布相同的行。 C#

我追加到Excel中,但是当我发布,我发现同一行已发布两次。 所以我有2行。 当我再次张贴,它离开我的第一行,覆盖第二行,但是然后给我一个副本作为第三行。

所以总而言之,我可以发布所有我需要的,只剩下1条重复的行。 我似乎无法纠正它

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsApp6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private static Microsoft.Office.Interop.Excel.Workbook mWorkBook; private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets; private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1; private static Microsoft.Office.Interop.Excel.Application oXL; private void button1_Click(object sender, EventArgs e) { string Combo1 = comboBox1.SelectedItem.ToString(); string path = @"C:\Users\Staff\Desktop\RIT\worksheet.xls"; oXL = new Microsoft.Office.Interop.Excel.Application(); oXL.Visible = true; oXL.DisplayAlerts = false; mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); mWorkSheets = mWorkBook.Worksheets; mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1"); Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange; //I thought issue maybe here.. int colCount = range.Columns.Count; int rowCount = range.Rows.Count; for (int index = 1; index < 3; index++) { mWSheet1.Cells[rowCount + index, 1] = rowCount + index; mWSheet1.Cells[rowCount + index, 1] = Combo1 + index; } mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value); mWSheet1 = null; mWorkBook = null; oXL.Quit(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } } } 

你必须使用

 for (int index = 2; index > 0; --index) { //... } 

而不是你的for循环,因为你会在循环的下一个循环中处理新插入/附加的行。 因此该行被插入两次,并且在下一次循环开始时它将被覆盖(正如你所提到的那样)。

从数组中删除某些东西的时候,你也可以使用这种循环(我把它称为从高到低的循环):在那里你会发生以下情况:

  • 你有一个item0,item1和item2的数组
  • 你开始从索引0处理数组
  • 如果一个条件通过(让我们把它放在索引0),你从数组中删除item0
  • 那么你增加柜台。

发生了什么?

  • 你刚刚删除了item0

一切都很好,直到这里:

  • 你现在有索引0的item1
  • 你现在有索引1的item2
  • 你的柜台已经在索引1了

所以你从处理中跳过item1。

反过来,你也发生了同样的情况:你增加了一行,并增加了一个使你在新插入/添加的行中的计数器。

所有的值都可以一次赋值:

 object[,] values = { { rowCount + 1, Combo1 + 1 }, { rowCount + 2, Combo1 + 2 } }; mWSheet1.Cells.Resize[2, 2].Offset[rowCount].Value2 = values;