我正在学习如何使用Interop.Excel。测试Winforms程序读取现有的Excel文件,检查是否存在名为“ Added_by_program”的选项卡,如果存在,则删除该工作表,并创建一个名为“ Added_by_program”的新工作表。如果我不尝试写新表,该程序将反复运行完美。尝试写时遇到问题。如果原始文件中没有该工作表,则该程序可以完美运行一次,并正确地写入新创建的工作表。但在随后的运行中,我得到:
“ System.Runtime.InteropServices.COMException:'该名称已被使用。尝试使用其他名称。'”
用于尝试命名新工作表的行。我必须手动杀死打开的Excel实例。我想念什么?
代码(删除了不相关的行)
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace excelReadWrite
{
public partial class Form1 : Form
{
string readFolder = myPath;
string inFileName = @"Aram test excel file.xlsx";
string newSheetName = "Added_by_program";
Range rawRange = null;
Range pasteRange = null;
int rawCols = 0;
int rawRows = 0;
int iInSheet = 0;
int iNewSheet = 0;
int nInSheets = 0;
bool foundRawSheet = false;
bool foundNewSheet = false;
Worksheet worksheet = null;
public Form1()
{
InitializeComponent();
}
private void start_Button_Click(object sender, EventArgs e)
{
string inFile = myPath+ inFileName;
int nSheets = 0;
string sheetNames = "";
// Open Excel workbook to read
Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = xl.Workbooks.Open(inFile);
// Count worksheets in opened Excel file
nSheets = workbook.Worksheets.Count;
nSheets_TextBox.Text = nSheets.ToString();
nInSheets = 0;
foreach (Worksheet worksheet in workbook.Worksheets)
++nInSheets;
//foreach (Worksheet worksheet in workbook.Worksheets)
for (int iSheet = nInSheets; iSheet >= 1; --iSheet)
{
worksheet = workbook.Worksheets[iSheet];
sheetNames += " " + worksheet.Name;
// The program is going to add a worksheet. If it already exists, delete it before adding it.
if (string.Equals(worksheet.Name, newSheetName))
{
workbook.Worksheets[iSheet].Delete();
}
}
// Add a new sheet and name it
if (foundRawSheet)
{
newWorksheet = workbook.Worksheets.Add();
newWorksheet.Name = newSheetName;
// THE NEXT LINE IS THE PROBLEM LINE
// "Written" WILL BE WRITTEN TO A1:C3 WHEN THE SHEET IS CREATED, BUT THIS LINE
// CAUSES THE ERROR IN SUBSEQUENT RUNS
// IF I COMMENT IT OUT, THE PROGRAM RUNS FINE, REPEATEDLY
newWorksheet.Range["A1", "C3"].Value2 = "Written";
workbook.Save();
workbook.Close();
xl.Quit();
}
}
}
答案 0 :(得分:1)
您设置了xl.DisplayAlerts=false
吗?
如果没有,则删除包含现有数据的工作表将导致显示确认对话框。
如果Excel应用程序可见,则Worksheet.Delete
将阻塞,直到确认对话框。
如果Excel应用程序不可见,您的代码将继续执行(该对话框已被有效取消->未确认删除),但不会删除工作表。