---
title: " C#操作excel sheet"
author: "hcmfys"
date: "2009-12-01T20:58:51Z"
tags: ["C", "C#", "C++", "Excel", "Microsoft"]
slug: "c-excel-sheet"
draft: false
lastmod: "2009-12-01T20:59:29Z"
id: 538532
url: "https://hcmfys.iteye.com/blog/538532"
---

\[code="java"] C#操作excel sheet 这里有个VB.NET利用数组的例子，自己改改好了 .NET下 从 DataView DataSet DataTable 导出数据至Excel Public Sub Exports2Excel(ByVal Dtg As DataGrid) If Dtg.VisibleRowCount &gt; 0 Then Try Me.Cursor = Cursors.WaitCursor Dim datav As New DataView If TypeOf Dtg.DataSource Is DataView Then datav = CType(Dtg.DataSource, DataView) ElseIf TypeOf Dtg.DataSource Is DataSet Then datav = CType(Dtg.DataSource, DataSet).Tables(0).DefaultView ElseIf TypeOf Dtg.DataSource Is DataTable Then datav = CType(Dtg.DataSource, DataTable).DefaultView End If Dim i, j As Integer Dim rows As Integer = datav.Table.Rows.Count Dim cols As Integer = datav.Table.Columns.Count Dim DataArray(rows - 1, cols - 1) As String Dim myExcel As Excel.Application = New Excel.Application For i = 0 To rows - 1 For j = 0 To cols - 1 DataArray(i, j) = datav.Table.Rows(i).Item(j) Next Next myExcel.Application.Workbooks.Add(True) myExcel.Visible = True For j = 0 To cols - 1 myExcel.Cells(1, j + 1) = datav.Table.Columns(j).ColumnName Next myExcel.Range("A2").Resize(rows, cols).Value = DataArray Catch exp As Exception MessageBox.Show("数据导出失败!请查看是否已经安装了Excel", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning) Finally Me.Cursor = Cursors.Default End Try Else MessageBox.Show("没有数据!", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub -------------------------------------------------------------------------------- 帮顶！ -------------------------------------------------------------------------------- 谢谢longdr(龙卷风)!这是我在ASP.NET下写的一个程序想转成WINFROM,偶对这个不熟,现找到一段源码:Excel.Application excel ; excel = new Excel.ApplicationClass(); Excel.WorkbookClass oWB; Excel.Worksheet oSheet; oWB = (Excel.WorkbookClass)(excel.Workbooks.Add(true)); oSheet = (Excel.Worksheet)oWB.ActiveSheet; oWB.Close(false,path,null); excel.Workbooks.Close(); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject (excel); System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB); System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet); oSheet = null; oWB= null; excel = null; 运行说缺using指令,请问需加载什么指令空间,并:这段代码能实现吗? -------------------------------------------------------------------------------- Response.Clear(); Response.Buffer= true; Response.Charset="GB2312"; Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls"); Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文 Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 this.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); this.DataGrid1.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); -------------------------------------------------------------------------------- 工程需引用MS-EXCEL -------------------------------------------------------------------------------- asxulong(假如再有约会) ,这是ASP.NET的代码吧,偶想要在WINFORM下的,谢了!! -------------------------------------------------------------------------------- longdr(龙卷风),怎么写?using MS-EXCEL?出错,提示"-"处应输入";". -------------------------------------------------------------------------------- HttpResponse res = HttpContext.Current.Response; res.Clear(); res.ContentType = "application/vnd.ms-excel"; res.Charset = ""; res.ContentEncoding= System.Text.Encoding.UTF8; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); this.mytd2.RenderControl(hw); string httpHeader="attachment;filename=report.Xls"; res.AppendHeader("Content-Disposition", httpHeader); res.Write(tw.ToString()); res.End(); -------------------------------------------------------------------------------- 呵呵，首先在工程引用微软的Excel库，如9.0或者10.0等 如果运行报错的话，可以考虑在源程序上方书写 using Excel=Microsoft.Office.Excel; 试一试，刚才那个导出程序在9.0是能跑的。 -------------------------------------------------------------------------------- longdr(龙卷风),现在可以运行了,但点击Button后没有生成EXCEL文档,没什么反应,以下是源码,看看是哪出错了,非常感谢! private void Form1\_Load(object sender, System.EventArgs e) { string oleinfo="Provider=Microsoft.Jet.OleDb.4.0; data source=D:\\\\项目备份 \\\\ok\\\\database\\\\ok.xls;Extended Properties=Excel 8.0;"; string strsel="SELECT 经理,\[1$].站号,脂肪,蛋白,干物质,酸度,煮后酸度,温度,细菌,搀假,搀假备注,感官,感官备注,酒精试验,酒精试验备注,煮沸试验,判定,收奶,收奶量 FROM \[1$] inner join \[2$] on \[1$].站号 like '%'+\[2$].站号+'%' where 收奶='拒收'order by 经理"; //string strsel="SELECT * FROM \[1$]"; OleDbConnection Myconn=new OleDbConnection(oleinfo); Myconn.Open(); OleDbDataAdapter Mycomm = new OleDbDataAdapter (strsel,Myconn) ; DataSet ds=new DataSet(); Mycomm.Fill(ds); Myconn.Close(); dataGrid1.DataMember= "\[1$]" ; dataGrid1.DataSource =ds; } private void button1\_Click(object sender, System.EventArgs e) { Excel.Application excel ; excel = new Excel.ApplicationClass(); Excel.WorkbookClass oWB; Excel.Worksheet oSheet; oWB = (Excel.WorkbookClass)(excel.Workbooks.Add(true)); oSheet = (Excel.Worksheet)oWB.ActiveSheet; oWB.Close(false,"ok",null); excel.Workbooks.Close(); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject (excel); System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB); System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet); oSheet = null; oWB= null; excel = null; } -------------------------------------------------------------------------------- oWB.Close(false,"ok",null); 是什么意思? 找到的源码是oWB.Close(false,path,null);我看path处该是表名,所以改了一下,对吗? -------------------------------------------------------------------------------- 高手快来救命啊!!自己顶!! -------------------------------------------------------------------------------- 呵呵，你都没有把数据导出到Excel去， 那又怎么会有反应呢？ -------------------------------------------------------------------------------- //datagrid内容到excel private void DatagridToExcel(DataGrid grid, Excel.Worksheet sheet) { DataTable table = (DataTable)grid.DataSource; int sheetRow = 1; //导出列头 for(int col = 0; col &lt; table.Columns.Count; col++) { sheet.Cells\[sheetRow, col + 1] = table.Columns\[col].ColumnName; } sheetRow++; //导出内容 for(int row = 0; row &lt; table.Rows.Count; row++) { for(int col = 0; col &lt; table.Columns.Count; col++) { sheet.Cells\[sheetRow, col + 1] = table.Rows\[row]\[col]; } sheetRow++; } } -------------------------------------------------------------------------------- 我也写了一个，自己试过了可以的 在mytable类中写 public void Binding(string sql,DataGrid dg) { DataSet ds = new DataSet(); //OleDbConnection MyConnection = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + System.Web.HttpContext.Current.Server.MapPath(".")+"/test.mdb"); OleDbConnection MyConnection = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + "VB.NET (F:):\\et1\\\\lianxi\\\\test.mdb"); OleDbDataAdapter MyCommand = new OleDbDataAdapter(sql,MyConnection); MyCommand.Fill(ds,"ta"); dg.DataSource = ds.Tables\["ta"].DefaultView; dg.DataBind(); } 然后private void Page\_Load(object sender, System.EventArgs e) { if(!IsPostBack) { MkTable mt = new MkTable(); mt.Binding("Select * from login",MyDataGrid); } // ページを初期化するユーザー コードをここに挿入します。 } private void button1\_Click(object sender, System.EventArgs e) { MyDataGrid.AllowPaging = false; MkTable mt = new MkTable(); mt.Binding("Select * from login",MyDataGrid); // MyDataGrid.SelectedItemStyle.BackColor=Color.white // MyDataGrid.AlternatingItemStyle.BackColor=Color.white // MyDataGrid.ItemStyle.BackColor=Color.white // MyDataGrid.HeaderStyle.BackColor=Color.white // MyDataGrid.HeaderStyle.ForeColor=Color.red HttpResponse resp = Page.Response; resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; //Me.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); MyDataGrid.RenderControl(hw); Response.Write(tw.ToString()); Response.End(); MyDataGrid.AllowPaging = true; mt.Binding("Select * from login",MyDataGrid); } OK了 -------------------------------------------------------------------------------- http://www.mscenter.edu.cn/blog/dragon1982/archive/2005/01/25/766.aspx -------------------------------------------------------------------------------- 生成表格,然后将其保存了Excle文件 //////////////////////////////////////////////////////////////////////////////生成报表 string contstr1="定期统计报告"; if (bjj=="1") { contstr += ""+getyymmddfang(enddatestr2)+"日均"; contstr += "日均差"; } contstr += ""; string filename="temp.htm";// string strInsert7 = "select * from gonghaobao"; if(pxxx=="1") { if(bjj=="0") { strInsert7 +=" order by first\_money desc,bm asc"; } else { strInsert7 +=" order by zengzhang\_money desc,first\_money desc,bm asc"; } } else if(pxxx=="3") { if(bjj=="0") { strInsert7 +=" order by bm desc,first\_money desc"; } else { strInsert7 +=" order by bm desc,zengzhang\_money desc"; } } else { strInsert7 +=" order by gonghao asc"; } myConn.Open ( ) ; if(myConn.State==System.Data.ConnectionState.Open)//判断myConn是否打开 { //int gonghaoint; OleDbCommand mycmd998=new OleDbCommand (strInsert7,myConn); OleDbDataReader sdr5566=mycmd998.ExecuteReader(); //第一层循环,按照工号进行读取 while(sdr5566.Read()) { //gonghaostr=sdr\["gonghao"].ToString(); contstr += ""; contstr += ""+sdr5566\["gonghao"].ToString()+""; contstr += ""+sdr5566\["zgname"].ToString()+""; contstr += ""+sdr5566\["bm"].ToString()+""; contstr += ""+sdr5566\["first\_money"].ToString()+""; if (bjj=="1") { contstr += ""+sdr5566\["end\_money"].ToString()+""; contstr += ""+sdr5566\["zengzhang\_money"].ToString()+""; } contstr += ""; } //统计 //查询语句 mycmd998.Dispose(); mycmd998=null; } contstr1=contstr1 + contstr; contstr1 += ""; if(bjj=="1") { contstr1 += "

备注:统计是:从"+getyymmddfang(stardatestr)+" 起"+getyymmddfang(enddatestr)+"与"+getyymmddfang(enddatestr2)+"的之间的日均

"; } else { contstr1 += "

备注:统计是:从"+getyymmddfang(stardatestr)+"起计算"+getyymmddfang(enddatestr)+"的日均

"; } contstr1 += "

"; contstr1 += ""; makehtm(contstr,"temp.xls");//生成Excel 其中makehtm函数为: private void makehtm(string contenstr,string filename) { string fisrtstr=Application.StartupPath+"//temp//"; using (StreamWriter sw = new StreamWriter(fisrtstr+filename)) { // Add some text to the file. sw.Write(contenstr); } } 这种方法是对简单的报表就合适. -------------------------------------------------------------------------------- lldwolf(铁背苍狼),你的程序我大概看懂了，只是在调用时 private void DatagridToExcel(DataGrid grid, Excel.Worksheet sheet) 第二个参数怎么写，我想新开一个ＥＸＣＥＬ文档。 -------------------------------------------------------------------------------- using System; using System.Data; using Excel; using System.Reflection; using System.Runtime.InteropServices; using System.IO; using System.Web; using System.Diagnostics; namespace HLDXS.NET.Comm { /// /// excel\_down 的摘要说明。 /// public class excel\_down:System.IDisposable { DataSet Excel\_DS; public excel\_down(DataSet Excel\_DS) { this.Excel\_DS=Excel\_DS; } public void Export\_Excel(System.Web.UI.Page excel) { Excel.Application MyApp; if(this.Excel\_DS.Tables.Count&lt;1) { return; } int table\_count=this.Excel\_DS.Tables.Count; object oMissiong = System.Reflection.Missing.Value; MyApp=new Excel.ApplicationClass(); Workbooks workbooks = MyApp.Workbooks; \_Workbook MyBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); Excel.Sheets mysheet=null; mysheet=MyApp.Worksheets; for(int i=0;i &lt;%@ Import Namespace="System.Data" %&gt; &lt;%@ Import Namespace="System.Data.ADO" %&gt;

Excel表格内容:

posted @ 2006-05-18 10:21 破茧化蝶 阅读(8) | 评论 (0) | 编辑 收藏 如何用c＃代码操作excel 通过自动化过程，使用诸如 Visual C# .NET 这样的语言编写的应用程序就可以用编程方式来控制其他应用程序。利用 Excel 的自动化功能，您可以执行诸如新建工作簿、向工作簿添加数据或创建图表等操作。对于 Excel 和其他 Microsoft Office 应用程序，几乎所有可以通过用户界面手动执行的操作也都可以通过使用“自动化”功能以编程方式来执行。 Excel 通过一种对象模型来公开这一程序功能。该对象模型是一些类和方法的集合，这些类和方法充当 Excel 的逻辑组件。例如，有 Application 对象、Workbook 对象和 Worksheet 对象，其中每一种对象都包含 Excel 中那些组件的功能。要从 Visual C# .NET 访问该对象模型，可以设置对类型库的项目引用。 本文将阐述如何为 Visual C# .NET 设置对 Excel 类型库的适当项目引用，并提供使 Excel 自动运行的代码示例。 为 Microsoft Excel 创建自动化客户端 1. 启动 Microsoft Visual Studio .NET。 2. 在文件菜单上，单击新建，然后单击项目。从 Visual C# 项目类型中选择 Windows 应用程序。Form1 是默认创建的窗体。 3. 添加对 Microsoft Excel 对象库的引用。为此，请按照下列步骤操作： a. 在项目菜单上，单击添加引用。 b. 在 COM 选项卡上，找到 Microsoft Excel 对象库，然后单击选择。 注意：Microsoft Office 2003 包含主 Interop 程序集 (PIA)。Microsoft Office XP 不包含 PIA，但您可以下载 PIA。 有关 Office XP PIA 的更多信息，请单击下面的文章编号，以查看 Microsoft 知识库中相应的文章： 328912 ( http://support.microsoft.com/kb/328912/ ) Microsoft Office XP 主 interop 程序集 (PIA) 可供下载 c. 在添加引用对话框中单击确定以接受您的选择。如果系统提示您为选定的库生成包装，请单击是。 4. 在视图菜单上，选择工具箱以显示工具箱，然后向 Form1 添加一个按钮。 5. 双击 Button1。出现该窗体的代码窗口。 6. 在代码窗口中，将以下代码 private void button1\_Click(object sender, System.EventArgs e) { } 替换为： private void button1\_Click(object sender, System.EventArgs e) { Excel.Application oXL; Excel.\_Workbook oWB; Excel.\_Worksheet oSheet; Excel.Range oRng; try { //Start Excel and get Application object. oXL = new Excel.Application(); oXL.Visible = true; //Get a new workbook. oWB = (Excel.\_Workbook)(oXL.Workbooks.Add( Missing.Value )); oSheet = (Excel.\_Worksheet)oWB.ActiveSheet; //Add table headers going cell by cell. oSheet.Cells\[1, 1] = "First Name"; oSheet.Cells\[1, 2] = "Last Name"; oSheet.Cells\[1, 3] = "Full Name"; oSheet.Cells\[1, 4] = "Salary"; //Format A1:D1 as bold, vertical alignment = center. oSheet.get\_Range("A1", "D1").Font.Bold = true; oSheet.get\_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; // Create an array to multiple values at once. string\[,] saNames = new string\[5,2]; saNames\[ 0, 0] = "John"; saNames\[ 0, 1] = "Smith"; saNames\[ 1, 0] = "Tom"; saNames\[ 1, 1] = "Brown"; saNames\[ 2, 0] = "Sue"; saNames\[ 2, 1] = "Thomas"; saNames\[ 3, 0] = "Jane"; saNames\[ 3, 1] = "Jones"; saNames\[ 4, 0] = "Adam"; saNames\[ 4, 1] = "Johnson"; //Fill A2:B6 with an array of values (First and Last Names). oSheet.get\_Range("A2", "B6").Value2 = saNames; //Fill C2:C6 with a relative formula (=A2 & " " & B2). oRng = oSheet.get\_Range("C2", "C6"); oRng.Formula = "=A2 & \\" \\" & B2"; //Fill D2:D6 with a formula(=RAND()\*100000) and apply format. oRng = oSheet.get\_Range("D2", "D6"); oRng.Formula = "=RAND()\*100000"; oRng.NumberFormat = "$0.00"; //AutoFit columns A:D. oRng = oSheet.get\_Range("A1", "D1"); oRng.EntireColumn.AutoFit(); //Manipulate a variable number of columns for Quarterly Sales Data. DisplayQuarterlySales(oSheet); //Make sure Excel is visible and give the user control //of Microsoft Excel's lifetime. oXL.Visible = true; oXL.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" ); } } private void DisplayQuarterlySales(Excel.\_Worksheet oWS) { Excel.\_Workbook oWB; Excel.Series oSeries; Excel.Range oResizeRange; Excel.\_Chart oChart; String sMsg; int iNumQtrs; //Determine how many quarters to display data for. for( iNumQtrs = 4; iNumQtrs &gt;= 2; iNumQtrs--) { sMsg = "Enter sales data for "; sMsg = String.Concat( sMsg, iNumQtrs ); sMsg = String.Concat( sMsg, " quarter(s)?"); DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?", MessageBoxButtons.YesNo ); if (iRet == DialogResult.Yes) break; } sMsg = "Displaying data for "; sMsg = String.Concat( sMsg, iNumQtrs ); sMsg = String.Concat( sMsg, " quarter(s)." ); MessageBox.Show( sMsg, "Quarterly Sales" ); //Starting at E1, fill headers for the number of columns selected. oResizeRange = oWS.get\_Range("E1", "E1").get\_Resize( Missing.Value, iNumQtrs); oResizeRange.Formula = "=\\"Q\\" & COLUMN()-4 & CHAR(10) & \\"Sales\\""; //Change the Orientation and WrapText properties for the headers. oResizeRange.Orientation = 38; oResizeRange.WrapText = true; //Fill the interior color of the headers. oResizeRange.Interior.ColorIndex = 36; //Fill the columns with a formula and apply a number format. oResizeRange = oWS.get\_Range("E2", "E6").get\_Resize( Missing.Value, iNumQtrs); oResizeRange.Formula = "=RAND()\*100"; oResizeRange.NumberFormat = "$0.00"; //Apply borders to the Sales data and headers. oResizeRange = oWS.get\_Range("E1", "E6").get\_Resize( Missing.Value, iNumQtrs); oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin; //Add a Totals formula for the sales data and apply a border. oResizeRange = oWS.get\_Range("E8", "E8").get\_Resize( Missing.Value, iNumQtrs); oResizeRange.Formula = "=SUM(E2:E6)"; oResizeRange.Borders.get\_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle = Excel.XlLineStyle.xlDouble; oResizeRange.Borders.get\_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight = Excel.XlBorderWeight.xlThick; //Add a Chart for the selected data. oWB = (Excel.\_Workbook)oWS.Parent; oChart = (Excel.\_Chart)oWB.Charts.Add( Missing.Value, Missing.Value, Missing.Value, Missing.Value ); //Use the ChartWizard to create a new chart from the selected data. oResizeRange = oWS.get\_Range("E2:E6", Missing.Value ).get\_Resize( Missing.Value, iNumQtrs); oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value, Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value ); oSeries = (Excel.Series)oChart.SeriesCollection(1); oSeries.XValues = oWS.get\_Range("A2", "A6"); for( int iRet = 1; iRet &lt;= iNumQtrs; iRet++) { oSeries = (Excel.Series)oChart.SeriesCollection(iRet); String seriesName; seriesName = "=\\"Q"; seriesName = String.Concat( seriesName, iRet ); seriesName = String.Concat( seriesName, "\\"" ); oSeries.Name = seriesName; } oChart.Location( Excel.XlChartLocation.xlLocationAsObject, oWS.Name ); //Move the chart so as not to cover your data. oResizeRange = (Excel.Range)oWS.Rows.get\_Item(10, Missing.Value ); oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top; oResizeRange = (Excel.Range)oWS.Columns.get\_Item(2, Missing.Value ); oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left; } 7. 滚动到代码窗口的顶部。将下面的代码行添加到 using 指令列表的末尾： using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; 对自动化客户端进行测试 1. 按 F5 生成并运行该程序。 2. 在窗体上，单击 Button1。该程序将启动 Excel 并将数据填充到一个新的工作表中。 3. 在提示您输入季度销售数据时，单击是。一个链接到季度数据的图表就会被添加到工作表中。 \[/code]