在做一个小项目,需要把一些查询结果导出到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" );
}
}

c#中使用excel的更多相关文章

  1. 【转】js 中导出excel 较长数字串会变为科学计数法

    [转]js 中导出excel 较长数字串会变成科学计数法 在做项目中,碰到如题的问题.比如要将居民的信息导出到excel中,居民的身份证号码因为长度过长(大于10位),excel会自动的将过长的数字串 ...

  2. 在VBA中调用excel函数

    以前不太会用VBA时,都是在excel中使用函数来计算一些数据.毕竟函数不如代码,效率比较低.所以,就学着怎么在VBA中引用Excel函数.平时我用得比较多的函数就是countif和sumif函数.1 ...

  3. UpdatePanel 中 导出Excel按钮

    UpdatePanel 中 导出Excel按钮 要加 Triggers </ContentTemplate> <Triggers> <asp:PostBackTrigge ...

  4. asp.net中导出Excel的方法

    一.asp.net中导出Excel的方法: 本文转载 在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上:一种是将文件直接将文件输出 ...

  5. ASP.net中导出Excel的简单方法介绍

    下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...

  6. 报表中的Excel操作之Aspose.Cells(Excel模板)

    原文:报表中的Excel操作之Aspose.Cells(Excel模板) 本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件.这个组件的强大之处,就不多说,对于我们的报表总是会有导 ...

  7. C#中对Excel进行操作

    工作中要处理一批数据,主要是处理从别处导出来的Excel表格(大概有一千多行,三十多列),拿到表格对Excel表格进行分析,按照一定的规则进行拆分成为一万多行的数据:首先这个需求要用程序进行处理的背景 ...

  8. j2e中操作EXCEL

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

  9. 【NPOI】通过NPOI从内存流中创建EXCEL

    一言不合就开始帖代码 XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作簿 XSSFSheet sheet = (XSSFSheet)workbook ...

  10. [R语言]读取文件夹下所有子文件夹中的excel文件,并根据分类合并。

    解决的问题:需要读取某个大文件夹下所有子文件夹中的excel文件,并汇总,汇总文件中需要包含的2部分的信息:1.该条数据来源于哪个子文件夹:2.该条数据来源于哪个excel文件.最终,按照子文件夹单独 ...

随机推荐

  1. webdriver +浏览器驱动

    webdriver 经常使用的驱动有ChromeDriver , Firefox 驱动和IE驱动. 在使用的时候需要将对应的驱动下载到本地放到Python的安装路径下,然后添加路径到系统环境变量. 有 ...

  2. Day 1: ASP.NET and JavaScript Jan.16th Trying

    ASP.NET has its own named controls(tags) corresponding to that in an HTML document, such as <asp: ...

  3. Js/对数组的认识。

    1.是对数组的声明:   var auditTaskIds = []; 我一般的写法.   var auditTaskIds1 = [];  2.向数组中添加元素:   auditTaskIds.pu ...

  4. 洛谷P1019:单词接龙(DFS)

    题目描述 单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的"龙"(每个单词都最多在"龙" ...

  5. centos7通过yum安装mysql,并授权远程连接 【转】

    http://blog.csdn.net/u012367513/article/details/40538267 用于备忘

  6. 解决yii2 禁用layout时AppAsset不加载资源的问题

    大王派我来巡山_site:http://blog.csdn.net/wang78699425/article/details/52369841 最近由于项目(yii2 的一个项目)需要,登录页面不需要 ...

  7. Android引入动态库so的方法

    Android引入动态库so的方法 标签(空格分隔): Android so 第三方库 为了执行效率,会将一些CPU密集性任务如音视频解码.图像处理等放入到so中,还有也会将程序关键核心部分放入到so ...

  8. MySQL Error--打开过多文件导致数据库无法连接

    [此文抄自同事的邮件,当作笔记学习] 环境描述Mysql 5.5.21OS centos 5.8zabbix agent 2.4.3 情况描述现象数据库处于运行状态,但是无法创建新的连接,监控报警数据 ...

  9. 第十一章 IO流

    11.IO流 11.1 java.io.File类的使用 1课时 11.2 IO原理及流的分类 1课时 11.3 节点流(或文件流) 1课时 11.4 缓冲流 1课时 11.5 转换流 1课时 11. ...

  10. varchar字数

    每行数据最多65000字节 长度是当前字符集的字符长度,而不是字节长度! 参考:https://www.cnblogs.com/billyxp/p/3548540.html 经常变化的字段用varch ...