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
我在这里做错了吗?对此的任何帮助都会很棒 寻找解决方案
答案 0 :(得分:5)
我使用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)
{
}
}
<强>更新强>
您可以在以下位置找到类似的解释/示例: http://www.dotnetperls.com/excel
Marshal.ReleaseComObject(book); // do this after the close
另外,有关清理Excel / COM的讨论很好...... How To Properly Clean Up Excel Interop Objects In c#