网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > C#应用
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
本月文章推荐
.C#使用指针.
.在C#中实现Socket端口复用.
.C#的Windows编程中多语言的实现.
.C#3.0 中的扩展方法 (Extension .
.c#实现google样式的分页.
.C#算法设计与分析-寻找素数.
.总结C#中得到程序当前工作目录和.
.用http代理下载sourceforge的cvs.
.用API得到局域网中可用SqlServer.
.用C#绘制实时曲线图.
.关于正则表达式匹配无异常资源耗.
.Visual C#的SQL Server编程.
.在C#里使用using操作符.
.发送邮件程序(Csharp2005).
.C#多线程-不同线程之间通过事件委.
.C#2.0新的语法扩充(泛型,迭代器,.
.用C#开发智能手机软件:推箱子(二.
.C#中水晶按钮的程序生成.
.C#中加强ListView控件的功能.
.使用c#操作IBM WebSphere MQ.

C#源码读取excel数据到程序中-SQL SERVER-到dataset中

发表日期:2007-4-30


一、将excel数据只读到程序中显示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace ExcelDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();  

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass app = new ApplicationClass();
            app.Visible = false;
          
            WorkbookClass w = (WorkbookClass)app.Workbooks.Open(@"C:\Documents and Settings\qqq\桌面\002.xls", //Environment.CurrentDirectory+
                Missing.Value,                Missing.Value,                Missing.Value,

                Missing.Value,                Missing.Value,                Missing.Value,

                Missing.Value,                Missing.Value,                Missing.Value,

                Missing.Value,                Missing.Value,                Missing.Value,

                Missing.Value,                Missing.Value);

           
            object missing = Type.Missing;          
            Sheets sheets = w.Worksheets;
            Worksheet datasheet = null;
            foreach (Worksheet sheet in sheets)
            {
                if (sheet.Name == "Recovered_Sheet1")
                {
                    datasheet = sheet;
                    break;
                }
            }
            if (null == datasheet)
            {
                MessageBox.Show(this, "没有名称为 Recovered_Sheet1 的Sheet.");
                return;
            }
         
            Range range = datasheet.get_Range("A8","N35");

            System.Array values = (System.Array)range.Formula;
            if (values != null)
            {
                int len1 = values.GetLength(0);
                int len2 = values.GetLength(1);

                for (int i = 1; i <= len1; i++)
                {
                    this.textBox1.Text += "\r\n";
                    for (int j = 1; j <= len2; j++)
                    {
                        if (values.GetValue(i, j).ToString().Length == 0)
                            this.textBox1.Text += "\t\t";
                        this.textBox1.Text += "\t" + values.GetValue(i, j).ToString();
                    }
                }
            }

            app.Quit();
            app = null;           
        }
    }

二、读取到dataset中/从dataset中写入sql server:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.OleDb;

namespace ExcelDemo
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 读取Excel文档
        /// </summary>
        /// <param name="Path">文件名称</param>
        /// <returns>返回一个数据集</returns>
        public DataSet ExcelToDS(string Path)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [Recovered_Sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds);
            return ds;
        }

        /// <summary>
        /// 写入Excel文档
        /// </summary>
        /// <param name="Path">文件名称</param>
        //public bool SaveFP2toExcel(string Path)
        //{
        //    try
        //    {
        //        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
        //        OleDbConnection conn = new OleDbConnection(strConn);
        //        conn.Open();
        //        System.Data.OleDb.OleDbCommand cmd = new OleDbCommand();
        //        cmd.Connection = conn;
        //        //cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'";
        //        //cmd.ExecuteNonQuery ();
        //        for (int i = 0; i < fp2.Sheets[0].RowCount - 1; i++)
        //        {
        //            if (fp2.Sheets[0].Cells[i, 0].Text != "")
        //            {
        //                cmd.CommandText = "INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('" + fp2.Sheets[0].Cells[i, 0].Text + "','" +
        //                fp2.Sheets[0].Cells[i, 1].Text + "','" + fp2.Sheets[0].Cells[i, 2].Text + "','" + fp2.Sheets[0].Cells[i, 3].Text +
        //                "','" + fp2.Sheets[0].Cells[i, 4].Text + "','" + fp2.Sheets[0].Cells[i, 5].Text + "')";
        //                cmd.ExecuteNonQuery();
        //            }
        //        }
        //        conn.Close();
        //        return true;
        //    }
        //    catch (System.Data.OleDb.OleDbException ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine("写入Excel发生错误:" + ex.Message);
        //    }
        //    return false;
        //}

        private void Form2_Load(object sender, EventArgs e)
        {
            DataSet ds=ExcelToDS(@"C:\Documents and Settings\qqq\桌面\002.xls");
            int x = ds.Tables.Count;           
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.AddRange(
                new DataColumn[]{
               
                    new DataColumn("col1",typeof(string)),
                    new DataColumn("col2",typeof(string)),
                    new DataColumn("col3",typeof(string)),
                    new DataColumn("col4",typeof(string)),
                    new DataColumn("col5",typeof(string)),
                    new DataColumn("col6",typeof(string)),
                    new DataColumn("col7",typeof(string)),
                    new DataColumn("col8",typeof(string)),
                    new DataColumn("col9",typeof(string)),
                    new DataColumn("col10",typeof(string)),
                    new DataColumn("col11",typeof(string)),
                    new DataColumn("col12",typeof(string)),
                    new DataColumn("col13",typeof(string)),
                    new DataColumn("col14",typeof(string))
                });

                for(int i=0;i<ds.Tables[0].Rows.Count;i++)
                {

                    if (ds.Tables[0].Rows[i][13].ToString().Length <= 0)
                        continue;
                    DataRow dr=dt.NewRow();

                    dr.ItemArray=ds.Tables[0].Rows[i].ItemArray;

                   dt.Rows.Add(dr);

              }
            this.dataGridView1.DataSource=dt;
            this.dataGridView1.AutoGenerateColumns=false;

            }
           
        }

    }

上一篇:C#分析数据库结构,使用XSL模板自动生成代码 人气:5409
下一篇:病毒及流氓软件自我复制的简单实现(C#) 人气:5689
浏览全部C#的内容 Dreamweaver插件下载 网页广告代码 祝你圣诞节快乐 2009年新年快乐