分享

用C#输出数据到excel的最简单的例子(By?kiseigo)

 goodwangLib 2012-02-17

用C#输出数据到excel的最简单的例子(By kiseigo)

  (2009-01-12 12:31:53)

    我安装的是VS2005, Office2003,2009.01.12中午成功运行。ps: 必须保证电脑安装了excel。

    首先,在解决方案资源管理器的引用文件夹右键“添加引用”,"COM"-Microsoft Excel 11.0 Object Library,这时回自动生成3个引用: Excel, Microsoft.Office.Core, VBIDE。

   如图:

   用C#输出数据到excel的最简单的例子(By <wbr>kiseigo)

    手工在前面添加using System.Reflection; 因为Missing.Value可能要用到很多次。最好不要添加excel的引用因为会引起混淆。

    代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace ExcelOutput
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnExcelOutput_Click(object sender, EventArgs e)
        {
            Excel.Application excel = new Excel.ApplicationClass();

            try
            {
                Excel.Workbook book = excel.Workbooks.Add(Missing.Value); // 添加一个工作簿

                Excel.Worksheet sheet = (Excel.Worksheet)excel.ActiveSheet;// 获取当前工作表
                sheet.Name = "sheetName1"; // 修改工作表的名字
                sheet.Cells[1, 1] = "333"; // 关键是,不管是Sheets[i]还是Cells[i,j]都是从1开始的,而不是从0开始的!!

                excel.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                excel.Quit();
                excel = null;
            }
        }
    }
}

 

我花了2天时间老是出异常,原来是因为sheet.Cells[0, 0]不存在!! 下标是从1开始的

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多