您的位置:首页 > Web前端 > HTML

C#第三次作业 Excel数据读取 及 HTML文件初步

2015-05-07 12:44 429 查看
目标2:把“姓名”和“作业网址”,转换为HTML识别的链接形式,相应的HTML文件名为
ex03_demo.html。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;
using System.IO;

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

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();//定义一个“打开文件对话框”openfile
openfile.Filter = "工作薄(*.xls)|*.xls|所有文件(*.*)|*.*";//Filter 决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容
if (openfile.FilterIndex == 1 && openfile.ShowDialog() == DialogResult.OK)//按了确认后
{
DataSet ds = ExcelToDS(openfile.FileName);//DataSet可以当成内存中的数据库
PrintRows(ds);
}
}
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;// OleDbDataAdapter 用于填充DataSet和更新资源,定义了myCommand为空
DataSet ds = null;
strExcel = "select * from [sheet1$]";//选择文件的sheet1这个表
myCommand = new OleDbDataAdapter(strExcel, strConn);//myCommand里有数据了
DataTable table1 = new DataTable();
ds = new DataSet();

//数据表DataTable 添加到 DataSet中
ds.Tables.Add(table1);

myCommand.Fill(table1);
dataGridView1.DataSource = table1;//dataGridView1显示tabel1

return ds;
}
private void PrintRows(DataSet dataSet)
{
using (StreamWriter sw = new StreamWriter("F:/ex03_demo.html", false, Encoding.Default))
{
//写HTML文件头部
sw.WriteLine("<html>\r\n <head>\r\n <title>我们的网页</title>\r\n </head> \r\n <body>");

String strName = "小王";
String strWebsite = "http://303727350.qzone.qq.com";
// For each table in the DataSet, print the row values.
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
//Console.WriteLine(row[column]);
if (column.ColumnName == "姓名")
strName = (String)row[column];
if (column.ColumnName == "作业网址")
strWebsite = (String)row[column];
//sw.WriteLine(row[column]);
}
// <a href="http://user.qzone.qq.com/807167573/2">杨明明</a> <br />
sw.WriteLine(@"<a href=""" + strWebsite + @""">        " + strName + @"</a> <br />");
}
}
//写HTML文件结尾  </body> </html>
sw.WriteLine("</body> \r\n </html>");
}
}
}
}


运行结果:点击打开文件并确定的同时,在DataGridView打开了excel并且生产了html文件





感想:这次的作业很多都不是很明白,主要参考了老师的代码,再一句一句的注释去看每个方法是怎么用,对于读取excel有一个初步的理解和印象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: