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;
二、示例程序
- 在Visual Studio .NET中建立一个C# WinForm工程.
- 添加Microsoft Excel Object Library引用:
- 右键单击Project , 选“添加引用”
- 在COM 标签项,选中 locate Microsoft Excel Object Library
- 点确定按钮完成添加引用。 On the View menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1.
- 在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" );
}
}
c#中使用excel的更多相关文章
- 【转】js 中导出excel 较长数字串会变为科学计数法
[转]js 中导出excel 较长数字串会变成科学计数法 在做项目中,碰到如题的问题.比如要将居民的信息导出到excel中,居民的身份证号码因为长度过长(大于10位),excel会自动的将过长的数字串 ...
- 在VBA中调用excel函数
以前不太会用VBA时,都是在excel中使用函数来计算一些数据.毕竟函数不如代码,效率比较低.所以,就学着怎么在VBA中引用Excel函数.平时我用得比较多的函数就是countif和sumif函数.1 ...
- UpdatePanel 中 导出Excel按钮
UpdatePanel 中 导出Excel按钮 要加 Triggers </ContentTemplate> <Triggers> <asp:PostBackTrigge ...
- asp.net中导出Excel的方法
一.asp.net中导出Excel的方法: 本文转载 在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上:一种是将文件直接将文件输出 ...
- ASP.net中导出Excel的简单方法介绍
下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...
- 报表中的Excel操作之Aspose.Cells(Excel模板)
原文:报表中的Excel操作之Aspose.Cells(Excel模板) 本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件.这个组件的强大之处,就不多说,对于我们的报表总是会有导 ...
- C#中对Excel进行操作
工作中要处理一批数据,主要是处理从别处导出来的Excel表格(大概有一千多行,三十多列),拿到表格对Excel表格进行分析,按照一定的规则进行拆分成为一万多行的数据:首先这个需求要用程序进行处理的背景 ...
- j2e中操作EXCEL
在j2e中操作excel,无非2种情况,在这里我贴部分代码做个例子就OK,不管是导入和导出都是操作的都是流 1,导入,浏览器输入EXCEL到java后台解析 package action; impor ...
- 【NPOI】通过NPOI从内存流中创建EXCEL
一言不合就开始帖代码 XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作簿 XSSFSheet sheet = (XSSFSheet)workbook ...
- [R语言]读取文件夹下所有子文件夹中的excel文件,并根据分类合并。
解决的问题:需要读取某个大文件夹下所有子文件夹中的excel文件,并汇总,汇总文件中需要包含的2部分的信息:1.该条数据来源于哪个子文件夹:2.该条数据来源于哪个excel文件.最终,按照子文件夹单独 ...
随机推荐
- 忘记Linux用户密码怎么办?
忘记密码解决办法(centos6.5版本) 1.开机时,在此页面一直按ESC 2.然后进入以下界面时,按一下字母 “E” 键 (3)再按字母 “E” 键 (4)之后 输入 ...
- wordpress搭建自己的博客~
去官方网站下载wordpress,并解压缩.下载链接:https://cn.wordpress.org/ wordpress是一款开源的PHP框架,搭建个人博客网站最实用的选择之一,甚至你都不需要懂P ...
- http/ftp等的URL匹配正则表达式 ZT
网上流传着多种匹配URL的正则表达式版本,但我经过试验,最好用的还是从stackoverflow上查到的: (https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_| ...
- C# 开发Modbus Rtu客户端 modbus测试Demo,Modbus 串口通信 , 虚拟MODBUS-RTU测试
前言 本文将使用一个NuGet公开的组件技术来实现一个ModBus RTU的客户端,方便的对Modbus rtu的服务器进行读写,这个服务器可以是电脑端C#设计的,也可以是PLC实现的,也可以是其他任 ...
- Linux下截屏方法
参考百度经验 https://jingyan.baidu.com/article/48a42057c8e8dfa92525047c.html 第一种: 截屏部分画面并保存 快捷键Shift+PrtSc
- 关于C#中break和continue的认识
1.在昨天我在做循环处理的时候,遇到了break和continue的使用问题,今天来总结了一下, break: for (int i=0;i<5;i++) { a++; if(a==1) bre ...
- memcache 应用场景
一..memcache应用场景 1.应用场景一: 缓解数据库压力,提高交互速度.它的一个总原则是将经常需要从数据库读取的数据缓存在memcached中.这些数据也分为几类: (1).经常被读取并且实时 ...
- python调用mediainfo工具批量提取视频信息
写了2个脚本,分别是v1版本和v2版本 都是python调用mediainfo工具提取视频元数据信息 v1版本是使用pycharm中测试运行的,指定了视频路径 v2版本是最终交付给运营运行的,会把v2 ...
- 浅谈JavaScript函数重载
上个星期四下午,接到了网易的视频面试(前端实习生第二轮技术面试).面了一个多小时,自我感觉面试得很糟糕的,因为问到的很多问题都很难,根本回答不上来.不过那天晚上,还是很惊喜的接到了HR面电话.现在HR ...
- php 字符串固定长度,不够补充其他字符串
<?php $input = '456'; $var= str_pad($input,5,10,STR_PAD_LEFT); w3school手冊:http://www.w3school.com ...