zoukankan      html  css  js  c++  java
  • Import / export data in MS Excel using C#

    Sometimes we may require to generate Excel file from our reports,read from excel files to import data etc. This can be achieved using Office Interop (Office Automation) assemblies, but Office Automation in Web servers,got some issues;(More details: http://support.microsoft.com/kb/257757). The alternative is using OleDb provider. You may need to add one more attribute to connection string to connect to the Excel file. And connection string will be

    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;"

    Please note the “Extended Properties” attribute. This attribute helps us to query the excel file.

    Exporting Data from Data Table to Excel File.

    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;"
    // Establish a connection to the data source.
    using(OleDbConnection Connection = new OleDbConnection(connectionString))
    {
    Connection.Open()
    //creating a new Sheet with name sample and three columns with Heading firstname, lastname and email
    using(OleDbCommand command = new OleDbCommand())
    {
    command.Connection = Connection;
    command.CommandText = "CREATE TABLE [Sample$](FirstName Char(255), LastName char(255), Email char(255))";
    command.ExecuteNonQuery();
    }
    //Adding records to the Sample Worksheet
    using(OleDbCommand command = new OleDbCommand())
    {
    command.Connection = Connection;
    command.CommandText = "INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('Anuraj','P','anuraj.p@example.com')";
    command.ExecuteNonQuery();
    command.CommandText = "INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('sreekumar','vn','sreekumar.vn@example.com')";
    command.ExecuteNonQuery();
    }
    }

    Import the Data from Excel

    DataTable dt;
    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;"
    // Establish a connection to the data source.
    using(OleDbConnection Connection = new OleDbConnection(connectionString))
    {
    Connection.Open()
    //reading data from excel to Data Table
    using(OleDbCommand command = new OleDbCommand())
    {
    command.Connection = Connection;
    command.CommandText = "SELECT * FROM [Sample]";
    using(OleDbDataAdapter adapter =new OleDbDataAdapter())
    {
    adapter.SelectCommand = command;
    adapter.Fill(dt);
    }
    }
    }
  • 相关阅读:
    SQLServer分组加序号,只取某个对象指定条件的前几个
    SQLServer用with temptb AS临时表查询或者更新字段,将某个字段赋值成某个字段的值
    KMP算法
    java知识点
    程序接口设计的六大原则
    罗马数字转int
    使用github作为maven仓库存放发布自己的jar包依赖 实现多个项目公共部分代码的集中,避免团队中多个项目之间代码的复制粘贴
    java mybatis中大于号小于号的转义
    两个有序数组 A1 A2 的合并
    Mysql_设置root指定的ip访问或连接数据库
  • 原文地址:https://www.cnblogs.com/JoshuaDreaming/p/1797947.html
Copyright © 2011-2022 走看看