我追加到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打開,保存並關閉。但沒有發佈。 –