在做一个小项目,需要把一些查询结果导出到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. 莫烦tensorflow(9)-Save&Restore

    import tensorflow as tfimport numpy as np ##save to file#rember to define the same dtype and shape w ...

  2. spring jpa Pageable 分页之---多条件排序

    Sort sort = new Sort(Direction.ASC, "sort").and(new Sort(Direction.DESC, groupField));//排序 ...

  3. java获取泛型类型

    import com.alibaba.fastjson.TypeReference; return JSON.parseObject(str, new TypeReference<BaseRes ...

  4. install svn server in Ubuntu

    1. #安装服务 apt-get install subversionapt-get install libapache2-svnapt-get install apache2apt-get inst ...

  5. springMvc---跨服务器文件上传(实测总结)

    序言: 该案例是采用springMvc实现跨服务器图片上传功能,其中用到的主要类和工具有:CommonsMultipartResolver.jquery.form.js.如果要实现多个文件上传,只需要 ...

  6. Dynamics CRM Plug-in

    Plug-in 就是我们俗称的dll file 或者是assembly file. 里面有自定义的代码可以运行在服务器端 Plug-in Pipeline: 只有3个阶段可以做改动: Pre-Vali ...

  7. cliipblard.js 实现点击复制

    <script src="js/clipboard.min.js"></script> <script type="text/javascr ...

  8. Java面向对象 第5节 抽象类和接口

    一.抽象类和抽象方法 区分抽象方法和普通方法1)当一个方法被abstract修饰时,该方法成为抽象方法2)抽象类所在的类必须定义为抽象类3)抽象方法不会有具体的实现,而是在抽象类的子类中通过方法重写进 ...

  9. nodeppt:网页版 PPT

    资料 网址 github https://github.com/ksky521/nodeppt 网页版PPT(nodeppt 的介绍) http://deliazhi.com/2017/03/31/W ...

  10. 解决ubuntu16.04桌面左侧栏和顶部栏消失的问题

    重要事情说三遍! 不要轻易重装系统! 不要轻易重装系统! 不要轻易重装系统! 问题所在:误删了unity桌面. 解决方法: $sudo apt-get install unity