【发布时间】:2015-10-27 17:35:20
【问题描述】:
以下代码取自this tutorial,用于使用 C# 创建和保存 Excel 文件:
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsAppExcelTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCreateExcelFile_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkBook.SaveAs("csharp-Excel.xls",
Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
} // class
} // namespace
它似乎运行良好——我看到了 MessageBox 消息,我可以单步执行它而没有任何问题的迹象。但是该文件没有按原样保存到硬盘驱动器中。为什么不呢?
【问题讨论】:
-
消息说什么?你想在哪里保存? Windows 默认设置将阻止您保存到 C 的根目录,除非您以管理员身份运行 Visual Studio。
-
一切尽在代码中;消息是“Excel 文件已创建,您可以找到文件 c:\\csharp-Excel.xls”;它将它保存到根目录,因为在 SaveAs() 调用中没有给出文件夹。无论如何,它应该是,除非我错过了什么。
-
我误会了,我以为catch中的消息框正在显示。尝试右键单击 Visual Studio 并说以管理员身份运行,看看是否有帮助。或者指定一个路径,比如你的桌面。
标签: c# excel office-interop excel-interop ole-automation