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文件.最终,按照子文件夹单独 ...
随机推荐
- 世界上最好的Sed教程
这是一份世界上最好的sed教程,sed是unix系统下流编辑里的超人.最初我写这份说明是为了我的 第二本电子书,然而随后我决定把这份说明变成一本免费电子书预览的同时再次做为文章发布到这里. Sed说明 ...
- Add和AddRange的使用
Add 是每次将单个元素添加到集合里面 AddRange可以一次性添加多个元素到集合里面 AddRange例子: public static int ExecuteCommand(st ...
- Address localhost:1099 is already in use
在 ItelliJ idea中创建了Servlet,启动tomcat时系统报错: Error running Tomcat 7.0.47: Address localhost:1099 is alre ...
- C++调用ffmpeg.exe提取视频帧
有时候,我们获得一段视频,需要将其中的每一帧都提取出来,来进行一些相关的处理,这时候我们就可以需要用到ffmpeg.exe来进行视频帧的提取. ffmpeg简介:FFmpeg是一套可以用来记录.转换数 ...
- 位运算 - a^b
求 a 的 b 次方对 p 取模的值. 输入格式 三个整数 a,b,p ,在同一行用空格隔开. 输出格式 输出一个整数,表示a^b mod p的值. 数据范围 1≤a,b,p≤109 输入样例: 3 ...
- jmeter压测、操作数据库、分布式linux下运行、webservice接口测试、charles抓包
一.jmeter压测 在线程组中设置好,然后添加http请求,t添加聚合报告查看压力测试结果,如图: 一般压测时间10-15分钟,如果是稳定性测试,一般n*12小时,这些并发用户一直在请求. tps: ...
- 作用域&&闭包
在了解闭包之前,先了解作用域一,作用域简单来说就是变量和函数可以访问的范围,在es5中变量作用域一般分为全局作用域和局部作用域,这个主要依据是全局变量还是局部变量 情景1: <script> ...
- day05 判断敏感字符
1.判断一个字符是不是敏感字符: in 1.str v ="年龄多大了" if "大" in v: print("敏感") 2.list/t ...
- zookeeper集群和安装dubbo的管控台
准备三台服务器CentOs6: 192.168.37.132 192.168.37.128 192.168.37.131 1 将zookeeper的安装包分别解压到/usr/local/目录下 进入c ...
- solr增加中文分析器
我的solr版本是5.3.0 1将jar包ik-analyzer-solr5-5.x.jar放入sor的web-inf的lib里面 2 在web-inf下面新建classes目录,再新增三个配置文件: ...