在c#中保存一个excel文件
void excelsave() { try { ApplicationClass app = new ApplicationClass(); // the Excel application. Workbook book = null; Worksheet sheet = null; Range range = null; // the range object is used to hold the data app.Visible = false; app.ScreenUpdating = false; app.DisplayAlerts = false; string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); book = app.Workbooks.Open(@"E:\SSIS\ABC\Book1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); sheet = (Worksheet)book.Worksheets[1]; range = sheet.get_Range("A1", Missing.Value); range.Columns.ColumnWidth = 22.34; range = sheet.get_Range("B1", Missing.Value); range.Columns.ColumnWidth = 22.34; book.SaveAs(@"E:\SSIS\ABC\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception ex) { } }
在这里我打开一个Excel工作表,试图增加列的宽度,并需要使列标题为粗体并保存文档,现在文档没有得到保存。 我正在使用VS 2008,C#3.5
有什么我在这里做错了吗? 任何帮助,这将是一个伟大的解决scheme
我使用VS 2010和.NET 4运行以下代码,但是此代码仍然可以在您的环境中运行。 另外,我简化了一下你的代码。 希望这会让你朝着正确的方向前进。
static void excelsave() { try { Application app = new Application(); string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); Workbook book = app.Workbooks.Open(@"c:\test.xls"); Worksheet sheet = (Worksheet)book.Worksheets[1]; Range range = sheet.get_Range("A1"); range.Columns.ColumnWidth = 22.34; range = sheet.get_Range("B1"); range.Columns.ColumnWidth = 22.34; sheet.get_Range("A1", "B1").Font.Bold = true; book.SaveAs(@"c:\test2.xls"); // or book.Save(); book.Close(); } catch (Exception ex) { } }
UPDATE
你可以find一个类似的解释/你在做什么的例子: http : //www.dotnetperls.com/excel
Marshal.ReleaseComObject(book); // do this after the close
如何正确清理Excel Interop对象在C#