C#第三次作业

来源:互联网 发布:windows mstsc 编辑:程序博客网 时间:2024/06/05 19:58

程序目的:用C#读取Excel文件,并保存成HTML格式


代码如下:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Collections;using System.Data.OleDb;using System.IO;namespace WindowsFormsApplication9{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            OpenFileDialog openfile = new OpenFileDialog();            openfile.Filter = "工作薄(*.xls)|*.xls|所有文件(*.*)|*.*";            if (openfile.FilterIndex == 1 && openfile.ShowDialog() == DialogResult.OK)                ExcelToDS(openfile.FileName);        }        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 [sheet1$]";            myCommand = new OleDbDataAdapter(strExcel, strConn);            DataTable table1 = new DataTable();            ds = new DataSet();            myCommand.Fill(table1);            dataGridView1.DataSource = table1;            using (StreamWriter sw = new StreamWriter(@"D:\ex03_demo.html",false,Encoding.Default))            {                sw.WriteLine("<html>" + "\r\n"+"<body>");                sw.WriteLine("<p><center>姓名</center>" + "\r\n");                foreach (DataRow dr in table1.Rows)                {                    sw.WriteLine("<br>" + "\r\n"+"<br/>");                    sw.WriteLine("<center><a href=\"" + dr["作业网址"].ToString() + "\">" + dr["姓名"].ToString() + "</a></center>");                }                sw.WriteLine("</p>"+"</body>" + "\r\n" + "</html>");                sw.Flush();                sw.Close();            }                                return ds;        }    }}


结果截图

1.打开程序



2.添加文件



3.显示excel数据



4.打开生成的html文件



5.点击蔡金峰小朋友的名字跳转到他的作业的网页



0 0
原创粉丝点击