0

我正在尝试将数据导出到 Excel 模板。我在工作簿中有多个选项卡。我要导出到的工作表选项卡称为“可行性”。问题是:如何导出到这个特定的工作表名称?

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");
        }

    }
4

2 回答 2

0

运行 for 查看所有工作表,并查看名称是否匹配。

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];
}

我发布的方式是将 null 分配给您的 COM 变量。然后,如果 finally 语句中它不为 null,则调用 FinalReleaseComObject。这样,即使方法中存在异常,它也会被释放。

Excel进程未关闭

InteropExcel.Sheets sheets = null
try
{
  sheets = ....;
}
finally
{
  if (sheets != null)
  {
    Marshal.FinalReleaseComObject(sheets);
    sheets = null;
  }
}
于 2013-10-23T15:05:58.787 回答
0

您是否尝试过 Name 属性?检查此工作表文档:http: //msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.worksheet_members.aspx

于 2013-10-23T15:15:59.143 回答