ASP.NET generates an Excel file

xiaoxiao2021-03-05  26

I have encountered some problems that generate Excel in my work.

Find a lot of methods on the network, each has excellent and disadvantage.

Finally, I chose an Excel automation service using Office to generate an Excel file, that is, using the COM object provided by Excel.

The specific code is as follows:

Public static void createExcel () {for (int i = 0; i <1; i ) {string stafile = "d: // test // x"; system.reflection.Missing miss = system.reflection.Missing.Value; Excel.ApplicationClass m_objExcel = new Excel.ApplicationClass (); m_objExcel.Visible = false; Excel.Workbooks m_objBooks = (Excel.Workbooks) m_objExcel.Workbooks; Excel.Workbook m_objBook = (Excel.Workbook) (m_objBooks.Add (miss)) Excel.worksheet m_objsheet = (Excel.Worksheet) m_objbook.activesheet; // Write data to the Excel file Excel.Range Er = m_objsheet.get_range ((object) "A1", System.Reflection.Missing.Value); Er .Value2 = "dfadfa";

M_OBJBOOK.SAVEAS (Stafile I.Tostring () ". XLS", MISS, MISS, MISS, MISS, MISS, Excel.xlsaveasaccessMode.xlnochange, Miss, Miss, Miss, MISS, MISS, MISS, MISS, MISS, MISS, MISS, M_OBJBOOK.CLOSE (False, Miss, miss); m_objbooks.close (); m_objexcel.quit ();

System.Runtime.InteropServices.Marshal.ReleaseComObject (er); System.Runtime.InteropServices.Marshal.ReleaseComObject (m_objSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject (m_objBook); System.Runtime.InteropServices.Marshal.ReleaseComObject (m_objBooks ); System.Runtime.InteropServices.Marshal.ReleaseComobject (m_objexcel); gc.collect ();}}

I have seen similar approaches online, but they all have problems that cannot be released after using Excel; I found that every instance object must be released when I have been using the COM object. That is, the red part of the code.

Note: Use this code to reference the Excel components in the project. Another: I only did test under Office 2003 and determined that the object can be released. There is no corresponding test under other systems, please study it by yourself.

Software environment: .NET Framework 1.1 vs.Net 2003 Office2003 Windows2000 SP4

转载请注明原文地址:https://www.9cbs.com/read-34006.html

New Post(0)