C#读取Excel文件(第三次C#作业)

来源:互联网 发布:梅西和c罗谁厉害知乎 编辑:程序博客网 时间:2024/05/17 02:00

目标:了解c#读取Excel数据的方法 (读取ex03_demo.xls文件中的“姓名”和“作业网址”,保存到文本文件中(文件名:ex03_demo.txt))

源代码如下:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Collections;using System.Data.OleDb;namespace ExcelDemo{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            //打开excel文件            OpenFileDialog openfile = new OpenFileDialog();            openfile.Filter = "工作薄(*.xls)|*.xls|所有文件(*.*)|*.*";            if (openfile.FilterIndex == 1 && openfile.ShowDialog() == DialogResult.OK)                ExcelToDS(openfile.FileName);        }        public DataSet ExcelToDS(string path)//获取数据库DataSet的内容        {   //创建一个数据连接            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + @path + ";" + "Extended Properties=Excel 8.0;";            //连接数据库,访问Excel文件            OleDbConnection conn = new OleDbConnection(strConn);                        conn.Open();            string strExcel = "";            OleDbDataAdapter myCommand = null;            DataSet ds = null;            strExcel = "select 姓名,作业网址 from [sheet1$]";//选择姓名、作业网址两栏作为数据源            myCommand = new OleDbDataAdapter(strExcel, strConn);//将数据源加载到DataSet            DataTable table1 = new DataTable();//创建DataTable的对象table1            ds = new DataSet();            myCommand.Fill(table1);//将数据导入table1            dataGridView1.DataSource = table1;//将table1显示在dataGriView            return ds;        }     }}

运行结果如下图所示:

打开excel文件ex03-demo

读取文件内容


好久没编c#程序,今天看到丁老师发布的学期考核,才想起原来欠了这么多C#作业。重新看起c#的书和课程讲义,觉得挺陌生的,这个作业其实不难,只是好像上大学之后就没有像以前一样及时巩固课程内容,突然想起以前丁老师讲的一句话,0.1>0,行动说明一切才明白这两年不好的学习习惯造成我学什么考完试都还给老师了。

c#读取excel文件链接:http://www.cnblogs.com/bicabo/archive/2009/05/05/1449906.html

0 0
原创粉丝点击