C#做的一個在vs2010中導入Excel表格的功能


一:練習時發現問題   在vs調試的時候一遍一遍輸入數據十分的麻煩,數據多的話每調試一次就要輸入一次數據,十分的浪費時間,所以做成一個小功能可以將數據直接導入,節省時間。

二:過程       1.插入一個dataGridview 控件

                      2.插入並設置MenuStrip控件並設置屬性

  效果圖如下:

   3.准備一個Excel表格

  4.運行程序,,導入vs2010中。

三:程序代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 凱哥
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void 數據導入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
          
        }
        private void excel文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null; 
            dataGridView1.Rows.Clear();  
            dataGridView1.Columns.Clear();
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
            if (file.ShowDialog() == DialogResult.OK)
            {
                string fname = file.FileName;
                string strSource = @"provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fname + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                 OleDbConnection conn = new OleDbConnection(strSource);
                string sqlstring = @"SELECT * FROM [Sheet1$]";
                OleDbDataAdapter adapter = new OleDbDataAdapter(sqlstring, conn);
                DataSet da = new DataSet();
                adapter.Fill(da);
                dataGridView1.DataSource = da.Tables[0];
            }
            else
            { return; }
        }
    }
}
四:運行結果:
 
原Excel表格
 

導入后效果:

 

后續:運行剛開始出現如下截圖錯誤,但被我成功解決

      哈哈機智如我

 

 

 

 

 

 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM