2

我正在创建 Excel,如下所示:

     class Program
{
    private Excel.Application app = null;
    private Excel.Application worksheet = null;
    private Excel.Application workbook = null;
    private Excel.Application worksheet_range = null;

    //public Program()
    //{
    //    CreateExcelDoc();
    //}
    static void Main(string[] args)
    {
        Program obj = new Program();
        obj.CreateExcelDoc();
    }

    public void CreateExcelDoc()
    {
        try
        {
            app = new Excel.Application();
            if (app == null)
                return;
            app.Visible = true;
            workbook = app.Workbooks.Add(1);////error in this,saying "can not convert from Excel.Workbook to Excel.Application"

        }
        catch (Exception ex)
        {
            throw new Exception("CreateExcelDoc: Error" + ex.Message);
        }

    }
}

谁能告诉我哪里出错了?注意:我正在关注这个:http: //msdn.microsoft.com/en-us/library/ms173186%28v=vs.80%29.aspx

请给我任何不错的链接/解决方案。我正在使用 Windows 7 64 位操作系统。

谢谢。

4

1 回答 1

3

更改此声明:

    private Excel.Application app = null;
    private Excel.Application worksheet = null;
    private Excel.Application workbook = null;
    private Excel.Application worksheet_range = null;

到:

    private Excel.Application app = null;
    private Excel.Worksheet worksheet = null;
    private Excel.Workbook workbook = null;
    private Excel.Range worksheet_range = null;

您也可以完全按照以下代码:

    app.Visible = true; // or false if you don't want to show app.
    workbook  = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
    worksheet = (Worksheet)workbook.Worksheets[1];

    // Select the Excel cells, in the range c1 to c7 in the worksheet.
    worksheet_range  = worksheet.get_Range("C1", "C7");

编辑

您可以使用以下代码保存工作簿:

    workbook.SaveAs(@"C:\XMLCopy.xls",
    Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
    false, false, Excel.XlSaveAsAccessMode.xlNoChange,
    missing, missing, missing, missing, missing);

但是在Workbook保存后寻找资源释放方法。您需要关闭您的文件、您的应用程序和所有涉及的对象。

于 2013-05-27T11:32:50.937 回答