使用VSIUAL C#.NET操作Excel -把DataTable中的数据写入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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值