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

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

2015-05-24 16:42 363 查看
物联1121 201211672132 姚硕云

一、程序功能简介:

C#读取Excel文件(样本文件:ex03_demo.xls,http://pan.baidu.com/s/1rXDoE)
读取ex03_demo.xls文件中的“姓名”和“作业网址”,保存到文本文件中(文件名:ex03_demo.txt)

二、源程序如下:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Text;

using Excel = Microsoft.Office.Interop.Excel;
using System.IO;

namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
DataTable table1 = new DataTable();
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

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 = "";
strExcel = "select 姓名,作业网址 from [sheet1$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);

DataSet ds = new DataSet();
myCommand.Fill(table1);
dataGridView1.DataSource = table1;
conn.Close();

return ds;

}

private void button2_Click(object sender, EventArgs e)
{
string savefile = @"e:\ex03_demo.txt";
StreamWriter sw = new StreamWriter(savefile, false);
if (dataGridView1 != null)
{
int rowCount = dataGridView1.Rows.Count;
int colCount = dataGridView1.ColumnCount;
for (int i = 0; i < rowCount; i++)
{
string readstr = "";
for (int j = 0; j < colCount; j++)
{

if (dataGridView1.Rows[i].Cells[j].Value!=null)
readstr += dataGridView1.Rows[i].Cells[j].Value.ToString() + " ";

}
readstr += "\n";
if (readstr != null)
sw.WriteLine(readstr);
}
sw.Close();
MessageBox.Show("保存成功!");
}
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}
}
}
三、运行结果显示
(1)主界面





(2)导入表格









(3)点击“另存”





(4)生成txt文件





四、心得与体会
虽然这次作业选择了最简单的一个程序要求来完成,但是自己在实践操作过程中还是遇到了不少的问题,也花了一些时间。在我没有头绪,不知道问题该怎么解决的时候,很感谢那些愿意帮助我查找原因的同学,学习真的就是一个互帮互助的过程!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: