C#中通过COM读写Excel

   Excel2010和以前的2003、2000、97都使用正常,但Excel2007好像问题多多,没时间研究,要求开发环境安装Excel2010吧。如果是布署在服务器上使用,则无妨;如果是发布给一般用户使用,那么最好要求用户安装2010,否则,要在代码中加入很多兼容代码,连Quit都会报错。
   在Visual Studio .NET(我用的是VS2010)中建立一个C# WinForm工程,添加Microsoft Excel Object Library引用:右键单击Project或选择“项目”菜单 , 选“添加引用”,在COM 标签项,选中 locate Microsoft Excel Object Library 14(Excel2010是14,2007是12)。点确定按钮完成添加引用。 不知为何这里不像VB6一样用复选框来表示引用与否,这里只能添加,如果要去掉,则要到项目属性中去了。
  添加两个按钮btnExport和btnRead,双击进代码。这里有个插曲,我画了一个按钮,再复制一个,双击第二个进去,竟然仍是响应第一个按钮。仔细看看也没有形成按钮数组。什么顺事呢?最终发现要在设计器(Form1.Desigher.cs)中修改这一句:
this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
否则会仍然关联到btnExport_Click,——这应该是它的BUG吧?
  代码最前端:
using System.Reflection; 
using Excel = Microsoft.Office.Interop.Excel;
  我还另外加了这两句,或许不需要:
using Office = Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
  在类中声明两个全局的变量——注意别写到类外面去了,否则会报错:
Excel.Application objApp;
Excel._Workbook objBook;
其余的代码我就直接贴了:

namespace ExcelApp//(别怕,ExcelApp是我的工程名)
{
    public partial class frmMain : Form
    {
        Excel.Application objApp;
        Excel._Workbook objBook;

        public frmMain()
        {
            InitializeComponent();
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            Excel.Workbooks objBooks;
            Excel.Sheets objSheets;
            Excel._Worksheet objSheet;
            Excel.Range range;

            try
            {
                // Instantiate Excel and start a new workbook.
                objApp = new Excel.Application();
                objBooks = objApp.Workbooks;
                objBook = objBooks.Add(Missing.Value);
                objSheets = objBook.Worksheets;
                objSheet = (Excel._Worksheet)objSheets.get_Item(1);

                //Get the range where the starting cell has the address
                //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
                range = objSheet.get_Range("A1", Missing.Value);
                range = range.get_Resize(5, 5);

                if (false)  //true) 为了测试,可以换为true或false以执行不同代码
                {
                    //Create an array.
                    double[,] saRet = new double[5, 5];

                    //Fill the array.
                    for (long iRow = 0; iRow < 5; iRow++)
                    {
                        for (long iCol = 0; iCol < 5; iCol++)
                        {
                            //Put a counter in the cell.
                            saRet[iRow, iCol] = iRow * iCol;
                        }
                    }

                    //Set the range value to the array.
                    range.set_Value(Missing.Value, saRet);
                }

                else
                {
                    //Create an array.
                    string[,] saRet = new string[5, 5];

                    //Fill the array.
                    for (long iRow = 0; iRow < 5; iRow++)
                    {
                        for (long iCol = 0; iCol < 5; iCol++)
                        {
                            //Put the row and column address in the cell.
                            saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString();
                        }
                    }

                    //Set the range value to the array.
                    range.set_Value(Missing.Value, saRet);
                }

                //Return control of Excel to the user.
                objApp.Visible = true;
                objApp.UserControl = true;
            }
            catch (Exception theException)
            {
                String errorMessage;
                errorMessage = "Error: ";
                errorMessage = String.Concat(errorMessage, theException.Message);
                errorMessage = String.Concat(errorMessage, " Line: ");
                errorMessage = String.Concat(errorMessage, theException.Source);

                MessageBox.Show(errorMessage, "Error");
            }
        }
        private void btnRead_Click(object sender, EventArgs e)
        {
            Excel.Sheets objSheets;
            Excel._Worksheet objSheet;
            Excel.Range range;

            try
            {
                try
                {
                    //Get a reference to the first sheet of the workbook.
                    objSheets = objBook.Worksheets;
                    objSheet = (Excel._Worksheet)objSheets.get_Item(1);
                }

                catch (Exception theException)
                {
                    String errorMessage;
                    errorMessage = "Can't find the Excel workbook.  Try clicking Button1 " +
                       "to create an Excel workbook with data before running Button2.";

                    MessageBox.Show(errorMessage, "Missing Workbook?");

                    //You can't automate Excel if you can't find the data you created, so 
                    //leave the subroutine.
                    return;
                }

                //Get a range of data.
                range = objSheet.get_Range("A1", "E5");

                //Retrieve the data from the range.
                Object[,] saRet;
                saRet = (System.Object[,])range.get_Value(Missing.Value);

                //Determine the dimensions of the array.
                long iRows;
                long iCols;
                iRows = saRet.GetUpperBound(0);
                iCols = saRet.GetUpperBound(1);

                //Build a string that contains the data of the array.
                String valueString;
                valueString = "Array Data/n";

                for (long rowCounter = 1; rowCounter <= iRows; rowCounter++)
                {
                    for (long colCounter = 1; colCounter <= iCols; colCounter++)
                    {

                        //Write the next value into the string.
                        valueString = String.Concat(valueString,
                           saRet[rowCounter, colCounter].ToString() + ", ");
                    }

                    //Write in a new line.
                    valueString = String.Concat(valueString, "/n");
                }

                //Report the value of the array.
                MessageBox.Show(valueString, "Array Values");
            }

            catch (Exception theException)
            {
                String errorMessage;
                errorMessage = "Error: ";
                errorMessage = String.Concat(errorMessage, theException.Message);
                errorMessage = String.Concat(errorMessage, " Line: ");
                errorMessage = String.Concat(errorMessage, theException.Source);

                MessageBox.Show(errorMessage, "Error");
            }
        }
    }
}

    下面几句是显示指定文件z.xls中的A1单元格内容:

objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objApp.Workbooks.Open("R:\\z.xls");
//objBook = objBooks.Add(Missing.Value); //这句是新建一个文件的意思
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
range = objSheet.get_Range("A1", Missing.Value);
String s=(String)range.Value2.ToString();
MessageBox.Show(s, "!");

示例代码陆续添加中。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: "C" 是英文字母表的第三个字母。它是一个常见字母,常用于拼英语单词和形成各种语言的音节。在汉字,"C" 通常用来表示音译外来词,如 "咖啡"(coffee)和 "巧克力"(chocolate)。此外,"C" 也是大量商品和品牌的首字母缩,如 "Coca-Cola" 和 "Chanel"。 在计算机科学,“C” 代表一种编程语言,它是世界上最常用的程序设计语言之一。由于其简洁性和灵活性,C 语言被广泛用于开发操作系统、应用程序和嵌入式系统。它是一种强类型、结构化的语言,可以直接与硬件进行交互,并提供了丰富的库函数和工具,方便开发人员进行编程。C 语言也有一些衍生语言,如 C++ 和 C#,它们在 C 语言的基础上增加了更多的功能和特性。 此外,"C" 还有其他多种含义和用途。在音乐,"C" 是一个音符,代表音 "do"。在化学,"C" 是碳元素的化学符号,它是地球上最常见的化学元素之一。它在有机化学、生物化学和无机化学等多个领域都有重要的应用。此外,"C" 还可以表示摄氏温度单位和凯尔文温度的常数。 总之,"C" 是一个具有多重含义和不同用途的字母,它在字母表的位置和在不同领域的应用都赋予了它多样的意义和重要性。 ### 回答2: c是字母表的第三个字母,也是拉丁字母的一员。在英语,c的发音为/k/,是一个清爽有力的辅音音素。c通常与其他字母组合成不同的发音。例如,与a组合成ca的时候,c的发音变为/ka/,与h组合成ch的时候,c的发音变为/tʃ/。此外,c也可以与k互换使用,像cat和kat的发音是相同的。 在计算机科学领域,c也是一种非常重要的程序设计语言。由于它的效率和灵活性,c被广泛应用于操作系统、编译器、游戏开发等领域。c语言的语法简洁,易于学习和理解,但同时也要求程序员具备较高的细致观察和逻辑思维能力。 此外,c在化学代表着“碳”元素。碳是地球上的生命之源,它是有机物的基础,也是生物体的组成部分。碳具有四个电子,因此可以与其他原子形成很多化合物。碳的化合物在生命过程起着举足轻重的作用,比如糖类、脂类、蛋白质等都由碳组成。 总之,c作为字母、计算机语言和化学元素,都承载着重要的含义和作用。无论是语言、科学还是生命科学领域,c都是不可或缺的一部分。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值