我追加到Excel中,但是当我发布时,我发现同一行已发布两次。所以我有2条线。当我再次发布时,它会留下我的第一行,覆盖第二行,但随后又给我一个重复的第三行。附加到excel,但将相同的行张贴两次。 c#
所以总而言之,我可以发布我需要的所有东西,并且只剩下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();
}
}
}
请尝试使用'int index = 2;索引> 0; index - 'instead =>,除非您将在下一次迭代中重新处理新插入的行。这会导致双重插入。 – cramopy
你试过了吗?我提议的更改是否有效? – cramopy
谢谢你的回复。如果我把0,1或2,它不会发布任何东西。表单仍然可以打开并运行。 excel打开,保存并关闭。但没有发布。 –