C# 控件Excel

本文档展示了如何使用C#将数据写入Excel,包括创建Excel应用程序对象,填充单元格,处理多维数组,读取数据以及绘制图表。在过程中遇到了应用程序初始化失败、对象为null以及数据比较失败的问题。
摘要由CSDN通过智能技术生成

     /// <summary>
    /// 数据导出Excel
    /// </summary>
    public static class AutoExcelClass
    {
        /// <summary>
        /// 数据写入Excel
        /// </summary>
        public static int autoExcel()
        {
            //Creating new Excel.Application
            Application app = new Application();

            // ERROR: EXCEL couldn't be started
            if (app == null)
            {
                return 0;
            }

            // Making application visible
            app.Visible = true;

            //Getting the workbooks collection
            Workbooks workbooks = app.Workbooks;

            //Adding a new workbook
            _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);

            //Getting the worksheets collection
            Sheets  sheets = app.Worksheets;

            _Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
            // ERROR: worksheet == null
            if (worksheet == null)
            {
                return 0;
            }

            // Setting the value for cell

            // This paragraph puts the value 5 to the cell G1
            Range range1 = worksheet.get_Range("G1", Missing.Value);
            //ERROR: range1 == null
            if (range1 == null)
            {
                return 0;
            }
            const int nCells = 5;
            range1.Value2 = nCells;

            //This paragraph sends single dimension array to Excel
            Range range2 = worksheet.get_Range("A1", "E1");
            int[] array2 = new int[nCells];
            for (int i = 0; i < array2.GetLength(0); i++)
            {
                array2[i] = i + 1;
            }
            range2.Value2 = array2;

            //This paragraph sends two dimension array to Excel
            Range range3 = worksheet.get_Range

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值