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

c#第三次作业 C#读取Excel文件,并保存成HTML格式

2015-05-08 20:47 701 查看
【作业要求】

[b]1.
C#读取Excel文件


[/b]

[b][b]2.
保存成HTML格式


[/b][/b]

[b][b]3.用文本显示上一步保存内容(无聊的时候随便加的)[/b][/b]

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

namespace WindowsFormsApplication6
{
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)
{
DataSet ds = ExcelToDS(openfile.FileName);
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;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataTable table1 = new DataTable();
ds = new DataSet();
ds.Tables.Add(table1);
myCommand.Fill(table1);
dataGridView1.DataSource = table1;
return ds;

}
private void PrintRows(DataSet dataSet)
{
using (StreamWriter sw = new StreamWriter("D:/ex03_demo.html", false, Encoding.Default))
{
sw.WriteLine("<html>\r\n <head>\r\n <title>我们的网页</title>\r\n </head> \r\n <body>");
String strName = "小王";
String strWebsite = "http:\\549002798.qzone.qq.com";
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
if (column.ColumnName == "姓名")
strName = (String)row[column];
if (column.ColumnName == "作业网址")
strWebsite = (String)row[column];

}
sw.WriteLine(@"<a href=""" + strWebsite + @""">        " + strName + @"</a> <br />");

}
// Read and show each line from the file.
sw.WriteLine("</body> \r\n </html>");
}

}
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}

private void button1_Click_1(object sender, EventArgs e)
{

StreamReader hc = new StreamReader(@"D:\ex03_demo.html", UnicodeEncoding.GetEncoding("GB2312"));
string ss = hc.ReadToEnd();
MessageBox.Show(ss);

}

}
}
运行结果

[b][b]




[/b][/b]

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: