我正在尝试使用 c# 将我在 VBA 中编写的内容转换为可执行文件。我的想法是将某些公式写入现有的 Excel 工作簿。我有写入新工作簿的语法,但没有写入现有工作簿的语法。
问问题
366 次
2 回答
3
久经考验
using System;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
Namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
Public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
// Open a File
xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//////////////////////////////////////////////////////////
// REST OF THE CODE HERE TO INTERACT WITH THE WORKSHEET//
//////////////////////////////////////////////////////////
//Once done close and quit Excel
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
于 2012-07-05T21:49:33.497 回答
1
您可以通过该Workbooks.Open
方法执行此操作,本文提供了详细信息。
string workbookPath = "c:/SomeWorkBook.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Worksheets
然后,您可以通过该属性引用特定工作表。
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
于 2012-07-05T21:47:47.567 回答