c#中使用excel

在做一个小项目,需要把一些查询结果导出到Excel,找了一些资料,自己也总结出了一点方法,与大家共享。

一、首先简要描述一下如何操作Excel表

先要添加对Excel的引用。选择项目-〉添加引用-〉COM-〉添加Microsoft Excel 9.0。(不同的office讲会有不同版本的dll文件)。
using Excel;
using System.Reflection;

//产生一个Excel.Application的新进程
Excel.Application app = new Excel.Application();
if (app == null)
{
statusBar1.Text = "ERROR: EXCEL couldn‘‘t be started!";
return ;
}

app.Visible = true; //如果只想用程序控制该excel而不想让用户操作时候,可以设置为false
app.UserControl = true;

Workbooks workbooks =app.Workbooks;

_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); //根据模板产生新的workbook
// _Workbook workbook = workbooks.Add("c://a.xls"); //或者根据绝对路径打开工作簿文件a.xls

Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
if (worksheet == null)
{
statusBar1.Text = "ERROR: worksheet == null";
return;
}

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

二、示例程序

  1. 在Visual Studio .NET中建立一个C# WinForm工程.
  2. 添加Microsoft Excel Object Library引用:
    1. 右键单击Project , 选“添加引用”
    2. COM 标签项,选中 locate Microsoft Excel Object Library
    3. 点确定按钮完成添加引用。 On the View menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1.
  3. 在Form1上添加一个button1,双击 Button1,添加click事件的代码.把数组里的数据填到Excel表格。

首先添加引用:

using System.Reflection; 
          using Excel = Microsoft.Office.Interop.Excel;

     声明两个类的成员变量     
      Excel.Application objApp;
      Excel._Workbook objBook;

      private void button1_Click(object sender, System.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 (this.FillWithStrings.Checked == 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" );
         }
      }
					

4.在Form1上添加一个Button2,双击 Button2,添加click事件的代码,从Excel表格读数据到数组:

private void button2_Click(object sender, System.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" );
         }
      }
时间: 2024-08-12 09:18:22

c#中使用excel的相关文章

R中读取EXCEL 数据的方法

最近初学R语言,在R语言读入EXCEL数据格式文件的问题上遇到了困难,经过在网上搜索解决了这一问题,下面归纳几种方法,供大家分享: 第一:R中读取excel文件中的数据的路径: 假定在您的电脑有一个excel文件,原始的文件路径是:D:\work\data\1 如果直接把这个路径拷贝到R中,就会出现错误,原因是: \是escape character(转义符),\\才是真正的\字符,或者用/ 因此,在R中有两种方法读取该路径: 1:在R中输入一下路径:D:\\work\\data\\1     

在 SQL Server 中查询EXCEL 表中的数据遇到的各种问题

原文:在 SQL Server 中查询EXCEL 表中的数据遇到的各种问题 SELECT * FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0','Data Source="D:\KK.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...[Sheet1$] 问题: 消息 15281,级别 16,状态 1,第 1 行 SQL Server 阻止了对组件 'Ad Hoc Di

Delphi中控制Excel(转载)

用Delphi从数据库中取得资料,然后导出到Excel中做成报表是个不错的选择,因为Excel强大的报表功能那可是没话说前提Delphi中要 uses comobj;var Excel:Variant;一.Excel操作1.创建Excel对象Excel := CreateOleObject( Excel.Application );2.显示ExcelExcel.Visible:=true;3.更改标题Excel.Caption:=Excel的标题;4.退出ExcelExcel.Quit;二.工作

ASP.NET中读取excel内容并显示

项目中经常会用到把excel的文件内容导入到数据库中的,刚刚花了点时间,做了个例子,基本上能实现导入Excel后显示的功能吧,导入的excel文件得是xls,即是2003的.     代码思路如下:要读取的excel文件必得得是在本地硬盘,所以一般来说都是让远程用户选择自己硬盘上的Excel文件,然后把用户选择的文件上传到本地服务器上,再在本地服务器上进行操作.我把界面后置代码重要部分贴出来,大家自己慢慢看吧,都有注释了. C#代码   // 上传按钮 protected void btnUp_

js导出table中的EXCEL总结

导出EXCEL一般是用PHP做,但是项目中,有时候PHP后端工程师返回的数据不是我们想要的,作为前端开发工程师,把对应的数据编号转换为文字后,展示给用户,但是,需求要把数据同时导出一份EXCEl.无奈之下,我只能用js导出table中的数据了. 导出EXCEl一般是自己人用的,所以用js导出,因为js导出EXCEL一般情况下兼容性不是很好,很多只是兼容IE浏览器,还要设置在工具栏中进行设置才能导出,因为会相对比较烦.下面介绍几种方法: 一.js导出EXCEl带单元格合并[已验证,比较好用] //

Java中读取Excel功能实现_POI

这里使用apache的poi进行读取excel 1,新建javaproject 项目:TestExcel 2,导入包 包下载地址:http://poi.apache.org/download.html#POI-3.10-FINAL 百度网盘下载:http://pan.baidu.com/s/1i365mQT 导入根目录下.lib.ooxml-lib下的所有jar 4,操作读取excel import java.io.File; import java.io.IOException; import

vc中判断excel、word文件是否存在,删除excel文件

vc中判断excel文件是否存在,删除excel文件可以使用PathFileExists_和DeleteFile函数 但是,由于03以后excel的后缀改为.xlsx.所以,使用时需加后缀.xlsx. 如:PathFileExists(“C:\Users\tony-wt\Desktop\MyProject\11.xlsx”) vc中判断excel.word文件是否存在,删除excel文件

在ASP程序中打印Excel报表的新方法

目前,B/S模式(浏览器/服务器模式)成为企业网上首选的计算模式.由于B/S模式的特殊性,在C/S下相对较易实现的Excel报表打印功能在B/S下却成为一个难点.本人通过研究写了一个基于ASP程序的打印Excel报表的程序.本程序的特点是无须任何组件. Print.asp ------------------------------------------------ <html><title>打印Excel报表</title> <% '控制脚本语言 respon

android中生成excel

都说程序员不爽产品经理,其实有的时候遇到一些奇葩的后台开发人员也会很不顺心.最近项目有这样一个要求,要生成一个excel然后发邮件给客户.结果后台人员直接把这个功能扔给客户端,理由是后台不好实现.听到这也就只能自己实现了(分分钟就想来个螺旋王扣它头上).这篇博客讲下如下在android中生成excel表并存到本地.先看下生成后的效果图: 初始化数据 首先我们要先造下测试数据,这里我把数据写死在一个常量类Const中,如下: public class Const { public interfac

j2e中操作EXCEL

在j2e中操作excel,无非2种情况,在这里我贴部分代码做个例子就OK,不管是导入和导出都是操作的都是流 1,导入,浏览器输入EXCEL到java后台解析 package action; import java.io.OutputStream; import java.sql.ResultSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import