简体   繁体   English

C#的Excel。 如何通过工作簿/工作表作为参考

[英]c# excel. How pass workbook/sheet as reference

I want to pass an excel workbook/sheet as a reference between several functions in order to do different operations on it. 我想在几个函数之间传递一个excel工作簿/工作表作为参考,以便对其执行不同的操作。 I have been looking for hours and can't find out how to do this. 我一直在找几个小时,却找不到解决方法。 Is this not common practice to have multiple functions work on an excel sheet in this way? 以这种方式让多个功能在excel工作表上工作不是常见的做法吗? the below code doesn't work ..doesn't work if i pass by value either. 下面的代码不起作用..如果我也按值传递也不起作用。

'System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800401A8' ' 'System.Runtime.InteropServices.COMException:'来自HRESULT的异常:0x800401A8''

pass_ref(ref xlWorkSheet1);  //call this


void pass_ref(ref Excel.Worksheet sheet) {

        MessageBox.Show("Pass Ref:" + sheet.Name); //can't produce sheet name
    }
xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

pass_ref(xlWorkSheet1);


xlWorkBook.Close(true, misValue, misValue);

Found a workaround. 找到了解决方法。 Save the workbook before trying to pass the sheet off. 在尝试通过工作表之前,保存工作簿。 This worked. 这工作了。

There are 3 basic ways to deal with Office Formats, depending on wich ones you need to support. 有3种基本方法可以处理Office格式,具体取决于您需要支持的格式。 And another one altogether might be better: 另一个可能更好:

  • You only need the new Formats (xlsx). 您只需要新的格式(xlsx)。 You can use the OpenXML SDK or any of the Wrapper classes. 您可以使用OpenXML SDK或任何Wrapper类。 In a pinch you could use the ZipArchive and XMLReader classes to modify those formats too. 您可以在短时间内使用ZipArchive和XMLReader类来修改这些格式。 They are simply a bunch of XML files in a .zip container. 它们只是.zip容器中的一堆XML文件。
  • You need to support old and new. 您需要支持新旧版本。 The (t)rusty office COM interop is the usual way. 生锈的办公室COM互操作是通常的方法。 This is what you picked right now. 这就是您现在选择的。 Of course it requires office to be installed and does not work from non-Interactive (Services, Servers) on top of all the normal issues inherent with COM interop. 当然,除了COM互操作固有的所有常规问题之外,它还需要安装Office,并且不能从非交互(服务,服务器) 正常工作。 I would wager you run into one of those. 我打赌你碰到其中之一。
  • You need to support old and new 2: OleDB Provider. 您需要支持新旧2:OleDB Provider。 I was only told of this option and have no actuall knowledge of it. 我仅被告知此选项,对此一无所知。

I always advise going for the OpenXML SDK/Option 1. Rather limit the supported Formats then going back to the COM way. 我总是建议您使用OpenXML SDK / Option1。而不是先限制支持的格式,然后再回到COM方式。 OleDB would be my second bet, despite not knowing the details. 尽管不知道细节,OleDB还是我的第二选择。 COM is best left as a fallback solution if nothing else works. 如果没有其他方法,最好将COM作为备用解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM