码迷,mamicode.com
首页 > Windows程序 > 详细

c#读写excel

时间:2015-08-03 11:40:34      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

对于有些小型的程序,数据的存储,第一容量不是很大,且存储方便,并不不需要用户机上安装数据库那么麻烦。不妨采用excel存储的方式来实现数据的读写。

如果使用excel进行读写,需要引用一个叫Mrcrosoft.Ofiice.Interop.Excel.dll的类库。

并且需要在代码编辑区,添加命名空间

如下:

using Microsoft.Office.Interop.Excel;

*对excel表格进行读取数据,显示在datagridview1里

 //读取excel里面的数据
 private void readEXCEL()
        {
            //string Current;
            //Current = Directory.GetCurrentDirectory();
            //string filename = Current + @"\test.xls";
            try
            {
                ds.Clear();
                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + txt_path.Text + ";Extended Properties=‘Excel 12.0;HDR=NO;IMEX=1‘"))
                {


                    using (OleDbDataAdapter da = new OleDbDataAdapter("Select F1 as 姓名 , F2 as 电话号码 from [" + comboBox1.Text + "]", conn))
                    {
                        da.Fill(ds, "xlssheet");
                    }
                }
                dataGridView1.DataSource = ds.Tables["xlssheet"];
                dataGridView1.AutoGenerateColumns = true;
                dataGridView1.Columns[0].ReadOnly = false;
                dataGridView1.Columns[1].ReadOnly = true;
                dataGridView1.Columns[2].ReadOnly = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开EXCEL文件遇到错误,请检查是否合法的excel文件/n" + ex.Message);
            }
        }

*将数据写入excel中

 public bool WriteXLS(string filename)
        {

            Microsoft.Office.Interop.Excel.Application xls = new Microsoft.Office.Interop.Excel.Application();
            _Workbook book = xls.Workbooks.Open(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            _Worksheet sheet;
            xls.Visible = false;
            xls.DisplayAlerts = false;
           
            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets[i + 1];
                if (sheet.Name+"$" == comboBox1.Text)
                {
                    sheet.Cells[(row + 1), 1] = dataGridView1.Rows[row].Cells[1].Value.ToString();
                    sheet.Cells[(row + 1), 2] = dataGridView1.Rows[row].Cells[2].Value.ToString();
                    textBox1.Text = "成功";
                    break;
                }
                else
                {
                   
                    continue;
                }
            }
            book.Save();
            book.Close(false, Missing.Value, Missing.Value);
            xls.Quit();
            sheet = null;
            book = null;
            xls = null;
            GC.Collect();
            return true;
        }

另外需要提到的技巧是有关,怎么通过datagridview1显示的数据,直接在表格里面进行数据修改,然后会写进excel中。确保数据实时更新的问题。这需要使用datagridview1里面的dataGridView1_RowLeave事件和dataGridView1_CellDoubleClick事件配合使用。代码如下:

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.Columns[2].ReadOnly = true;
            //textBox1.Text = dataGridView1.Rows[row].Cells[1].Value.ToString();
            if (name == "" && number == "")
            {
                
            }
            else
            {
                //WriteXLS(txt_path.Text);//写入数据
                textBox1.Text = "success!";
                name = dataGridView1.Rows[row].Cells[1].Value.ToString();
                number = dataGridView1.Rows[row].Cells[2].Value.ToString();
                WriteXLS(txt_path.Text);
                name = "";
                number = "";
            }
        }
        int row=0;
        string name = string.Empty;
        string number = string.Empty;
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.Columns[1].ReadOnly = false;
            dataGridView1.Columns[2].ReadOnly = false;
            row = dataGridView1.CurrentRow.Index;
          
            name = dataGridView1.Rows[row].Cells[1].Value.ToString();
            number = dataGridView1.Rows[row].Cells[2].Value.ToString();
            if (name == "" && number == "") {
                name = number = "1";
            }

        }



c#读写excel

标签:

原文地址:http://my.oschina.net/RabbitXiao/blog/486998

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!