关闭

C#第三次作业:导入excel,并生成文本文件

标签: c#
155人阅读 评论(0) 收藏 举报
分类:

部分核心代码:

数据处理部分

        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 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);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string savefile = @"f:\data.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("文件已保存!");
            }
        }

演示效果:




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7271次
    • 积分:286
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:1篇
    • 译文:0篇
    • 评论:16条
    文章分类