C# 导出到特定的Excel工作表名称
我正在尝试将数据导出到Excel模板。工作簿中有多个选项卡。我要导出到的工作表选项卡称为“可行性”。问题是:如何导出到此特定工作表名称C# 导出到特定的Excel工作表名称,c#,excel,C#,Excel,我正在尝试将数据导出到Excel模板。工作簿中有多个选项卡。我要导出到的工作表选项卡称为“可行性”。问题是:如何导出到此特定工作表名称 using Excel = Microsoft.Office.Interop.Excel; //excel output variables private string excelFileName = SqlDB.GetFolderTemplates() + SqlDB.GetFileEngOrd(); private static Exce
using Excel = Microsoft.Office.Interop.Excel;
//excel output variables
private string excelFileName = SqlDB.GetFolderTemplates() + SqlDB.GetFileEngOrd();
private static Excel.Application xlsApp;
private static Excel.Workbooks workbooks;
private static Excel.Workbook workbook;
private Excel.Worksheet worksheet;
private void btnFeasibility_Click(object sender, EventArgs e)
{
xlsApp = new Excel.ApplicationClass();
if (xlsApp == null)
{
MessageBox.Show(Constants.EXCEL_INSTALL);
return;
}
try
{
xlsApp.Visible = true;
workbooks = xlsApp.Workbooks;
workbook = xlsApp.Workbooks.Open(excelFileName);
//PROBLEM IS HERE -- HOW CAN I GO TO THE WORKSHEET NAMED "FEASIBILITY"
worksheet = (Excel.Worksheet)workbook.Sheets[1];
worksheet.Select();
worksheet.Cells[3, 4] = newEngOrd.CustName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//release excel
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsApp);
xlsApp = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
MessageBox.Show("Export Complete");
}
}
对所有工作表进行一次检查,看看名称是否匹配
int foundNr=-1;
InteropExcel.Sheets sheets = workbook.Sheets;
InteropExcel.Sheet tempSheet = null;
for (int sheetIndex = 1; sheetIndex <= sheets.Count; sheetIndex++)
{
tempSheet = (InteropExcel.Worksheet)sheets[sheetIndex];
if (tempSheet.Name == "Feasibility")
{
foundNr = sheetIndex;
Marshal.FinalReleaseComObject(tempSheet);
tempSheet = null;
break
}
Marshal.FinalReleaseComObject(tempSheet);
tempSheet = null;
}
if (foundNr != -1)
{
sheet = (InteropExcel.Worksheet)sheets[foundNr];
}
你试过这个名字吗?
检查此工作表文档:我已编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。好的-学到了一些新的东西,谢谢。这找到了工作表并导出到它。但是,Excel.exe仍处于打开状态,未关闭。还有其他想法吗?我不想在Excel.exe上杀戮。该链接涵盖了您必须注意的大部分内容。摘要:1)确保释放所有互操作变量。2) 不要重复使用/重新分配任何变量。首先释放它。3) 不要在结构内部使用变量。(a.b=x;而不是c=a.b;c=x;然后发布c.)3)注释所有代码并添加回代码,直到它不发布。然后你就知道你的问题出在哪里了。在将所有打开的excel进程id导出到excel之前,我制作了一个哈希表。在导出之后,我杀死了不在哈希表中的进程id。不是很优雅,但它很有效。找到每个要发布的变量对我来说都是一项艰巨的任务,但它在发布Excel时并没有终止线程,即使对于非常复杂的Excel处理也是如此。我做了类似的事情来终止应用程序/停止调试。
InteropExcel.Sheets sheets = null
try
{
sheets = ....;
}
finally
{
if (sheets != null)
{
Marshal.FinalReleaseComObject(sheets);
sheets = null;
}
}