使用VSIUAL C#.NET操作Excel -把DataTable中的数据写入Excel

本文介绍如何使用C#编程语言将数据从数据库查询结果(DataTable)导出到Microsoft Excel工作簿。通过实例展示了创建Excel文件、填充数据及保存的具体步骤。
自动化允许由编程语言(如C#.NET等)创建的应用程序操作其它的应用程序。使用Excel自动化可以创建工作薄(Workbook)并为其添加数据或者创建一个图表。下面的示例演示了把DataSet中的数据导出到Excel中。
1.         新建C#.NET工程ExcelApp
2.         引用Com组件Microsoft.Excel 11.0 Object Library
3.         新建类ExcelProgram
using System;

using System.Data;

using System.Data.SqlClient;

using System.Reflection;

 

using Excel = Microsoft.Office.Interop.Excel;

 

namespace Avisnet

{

    
class ExcelProgram

    
{

        
static void Main(string[] args)

        
{

            ExcelProgram p 
= new ExcelProgram();

            DataTable table 
= p.LoadDataTable();

            p.ExportDataTable(table);

        }


 

        
public DataTable LoadDataTable()

        
{

            
string connString = "server=wangjs;User ID=sa;Password=sa;database=pubs;Connection Reset=FALSE";

 

            
using(SqlConnection conn = new SqlConnection(connString))

            
{

                DataSet ds 
= new DataSet();

                SqlDataAdapter adapter 
= new SqlDataAdapter("SELECT * FROM authors", conn);

                adapter.Fill(ds);

                
return ds.Tables[0];

            }


        }


 

        
public void ExportDataTable(DataTable table)

        
{

            
// Starts excel and gets an excel application object.

            Excel.Application excel 
= new Excel.Application();

 

            
// Adds a new workbook to the excel application.

            Excel.Workbook book 
= excel.Workbooks.Add(Missing.Value);

            Excel.Worksheet sheet 
= (Excel.Worksheet)book.ActiveSheet;

 

            
// Adds table headers

            
for(int col = 0; col < table.Columns.Count; col++)

            
{

                sheet.Cells[
1, col + 1= table.Columns[col].ColumnName;

            }


 

            
for(int row = 0; row < table.Rows.Count; row++)

            
{

                
for(int col = 0; col < table.Columns.Count; col++)

                
{

                    sheet.Cells[row 
+ 2, col + 1= table.Rows[row][col].ToString();

                }


            }


 

            
// Saves and cloeses the workbook;

            book.Close(
true"C:/fx.xls", Missing.Value);

 

            
// Exit excel application.

            excel.Quit();

        }


    }


}


 
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值