VS C#-Microsoft Excel对象库参考

时间:2018-10-10 08:41:39

标签: c#

编辑:

我正在尝试在Visual Studio C#中使用Microsoft Excel。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace write_data_to_excel
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();

            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            xlWorkSheet.Cells[1, 1] = "ID";
            xlWorkSheet.Cells[1, 2] = "Name";
            xlWorkSheet.Cells[2, 1] = "1";
            xlWorkSheet.Cells[3, 1] = "2";
            xlWorkSheet.Cells[3, 2] = "Two";

            xlWorkBook.SaveAs("C:\\examplewrite.xlsx", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();


        }
    }
}

错误:

System.Runtime.InteropServices.COMException:'无法访问'examplewrite.xlsx'。'

我正在使用VS Community 2017。

1 个答案:

答案 0 :(得分:2)

是的,它要求所有客户端计算机都必须安装相同版本的Microsoft Excel。

在此处找到更多信息:https://www.gemboxsoftware.com/spreadsheet/articles/c-sharp-microsoft-office-interop-excel-automation