c#如何访问打开的Excel文件?

请帮助我这个东西!

在我的新项目中,我需要访问一些Excel文件。 所有的名字都是已知的。 打开这个文件并写入数据很容易。如果excel对象被存储到列表中,那么在程序仍然运行时很容易重新访问已经打开的文件。 请看下面的例子。

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace ExcelTutorial { public partial class Form1 : Form { List<TextBox> textToExcel = new List<TextBox>(); List<string> s_excelFiles = new List<string> { "Workbook1.xlsx", "Workbook2.xlsx", "Workbook3.xlsx", "Workbook4.xlsx", "Workbook5.xlsx" }; List<Excel.Application> l_excelApplication = new List<Excel.Application>(); List<Excel.Workbook> l_excelWorkbook = new List<Excel.Workbook>(); List<Excel.Worksheet> l_excelWorksheet = new List<Excel.Worksheet>(); bool fileOpened = false; public Form1() { InitializeComponent(); textToExcel.Add(textBox1); textToExcel.Add(textBox2); textToExcel.Add(textBox3); textToExcel.Add(textBox4); textToExcel.Add(textBox5); } private void btn_Unopened_Click(object sender, EventArgs e) { string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath); if (fileOpened != true) { foreach (var item in s_excelFiles) { Excel.Application newExcelApp = new Excel.Application(); Excel.Workbook workbook = newExcelApp.Workbooks.Open(path + "\\" + item , ReadOnly: false, Editable: true); Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet; newExcelApp.Visible = true; ((Excel.Range)worksheet.Cells[1, 1]).Value = textToExcel[s_excelFiles.IndexOf(item)].Text; l_excelApplication.Add(newExcelApp); l_excelWorkbook.Add(workbook); l_excelWorksheet.Add(worksheet); } fileOpened = true; } else { foreach (var item in l_excelWorksheet) { ((Excel.Range)item.Cells[1, 1]).Value = textToExcel[l_excelWorksheet.IndexOf(item)].Text; } } } private void btn_Opened_Click(object sender, EventArgs e) { } } } 

但是,程序运行的时候用户有可能已经打开了工作簿。 很明显,Excel将消息发送给用户,要求重新打开工作簿。 这可能会导致数据丢失。 当然我可以在访问它之前检查文件是否打开, 这里用下面的代码来描述它:

 try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } 

然后只是要求用户closures该文件。 但我相信还有另一种方法可以做得更好。

所以,我的问题是:如何访问用户已经打开的文件?

ExcelTutorial解决scheme在这里可用!

您可以尝试下面的代码来访问当前的活动工作簿:

  //Gets Excel and gets Activeworkbook and worksheet Excel.Application oXL; Excel.Workbook oWB; Excel.Worksheet oSheet; oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); oXL.Visible = true; oWB = (Excel.Workbook)oXL.ActiveWorkbook; docProps = oWB.CustomDocumentProperties 

或者更好的解决scheme:

 using Excel = Microsoft.Office.Interop.Excel; using ExcelDna.Integration; // Get the currect application instance Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application; // Get active workbook Excel.Workbook wbook = xlapp.ActiveWorkbook; 

更多信息: 在C#中获取当前的工作簿对象