VS2010 C# DataGridView 导入导出EXECL




初衷:由于之前遇到了这个问题在网上搜索了许久才把代码给调试好了感觉有必要自己整理一下方便“在路上”的IT……


我的困惑:我用的是VS2010 & OFFICE2010 & SQL2008 在网上找一些控件添加些引用什么的都没有找到,说还要重装下,基本的顺序我在这说一下吧:一个纯净的系统,驱动,补丁,office, iis , .net , sql ;我不想重装所以就用了文件流......


//准备1:建一个类 apiconfig.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace 教务管理系统
{
    class apiconfig
    {
        //获取config.ini配置文件接点信息
        public static string getConfigFileValue(string section, string name)
        {
            String FileName = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "config.ini";
            StringBuilder temp = new StringBuilder(1000);
            ApiHelper.GetPrivateProfileString(section, name, "", temp, 1000, FileName);
            return temp.ToString();
        }
        /// 写配置文件ini
        //public static void WritePerConfigure(string section, string name, string itemvalue)
        //{
        //    String FileName = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Taobao.ini";
        //    ApiHelper.WritePrivateProfileString(section, name, itemvalue, FileName);
        //}
        public class ApiHelper
        {
            [DllImport("kernel32")]
            public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
            [DllImport("kernel32")]
            public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        }
    }
}



//准备2:建一个类common.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace 教务管理系统
{
    public class common
    {
        // 返回DataView的通用类
        public static DataView GetDataView(string sql)
        {
            DataSet dsReturn = new DataSet();
            DataView dvReturn = new DataView();
            using (SqlConnection conn = new SqlConnection(GetConnStr()))
            {
                dsReturn = ExecuteDataset(conn, CommandType.Text, sql, null);
                if (dsReturn.Tables.Count > 0)
                {
                    dvReturn = dsReturn.Tables[0].DefaultView;
                }
            }
            return dvReturn;
        }
        // 返回DataTable的通用类
        public static DataTable GetDataTable(string sql)
        {
            DataSet dsReturn = new DataSet();
            DataTable dtReturn = new DataTable();
            using (SqlConnection conn = new SqlConnection(GetConnStr()))
            {
                dsReturn = ExecuteDataset(conn, CommandType.Text, sql, null);
                if (dsReturn.Tables.Count > 0)
                {
                    dtReturn = dsReturn.Tables[0];
                }
            }
            return dtReturn;
        }
        //提交 update insert语句
        public static bool PostModify(string sql)
        {
            bool blresult = true;
            int i_result = ExecuteNonQuery(GetConnStr(), CommandType.Text, sql, null);
            if (i_result > 0)
            {
                blresult = true;
            }
            else
            {
                blresult = false;
            }
            return blresult;
        }
        public static string GetConnStr()
        {
            string server = apiconfig.getConfigFileValue("sqlserver", "server");
            string database = apiconfig.getConfigFileValue("sqlserver", "database");
            string uid = apiconfig.getConfigFileValue("sqlserver", "uid");
            string pwd = apiconfig.getConfigFileValue("sqlserver", "pwd");
            string strConn = "server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd + "";
            return strConn;
        }
        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            SqlCommand command = new SqlCommand();
            PrepareCommand(command, connection, null, commandType, commandText, commandParameters);
            IDataAdapter adapter = new SqlDataAdapter(command);
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet);
            command.Parameters.Clear();
            return dataSet;
        }
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        public static DataSet myselect(string tempstrsql)//调取数据
        {
            string sqlstr = tempstrsql;
            string connstr = "data source=(local);database=test;uid=sa;pwd=123";
            SqlConnection myconn = new SqlConnection(connstr);
            DataSet ds = new DataSet();//数据集
            SqlDataAdapter da = new SqlDataAdapter(sqlstr, myconn);
            ds.Clear();//清空数据集
            da.Fill(ds, "table");
            myconn.Close();//关闭连接对象
            return ds;
        }
    }
}


//准备3

在你根目录下的 bin\Debug文件下面 要有一个 config.ini 文件(类似于记事本) 里面的内容要修改成你数据库的信息为:


[sqlserver]

server=(local)

database=test

uid=sa

pwd=123


//准备4


xls中的数据要和数据库中的数据一一对应

162336231.png

162347559.png


开写:主要代码

注:命名空间(只准比我多 不能比我少):



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace 教务管理系统
{
    public partial class 考勤 : Form
    {
        public 考勤()
        {
            InitializeComponent();
        }
                  string work_time1 = "";
        string work_time2 = "";
        //导入 button1 为选择文件按钮 ,button2为导入按钮,button3是导出按钮
        priate void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = @"C:\Users\Administrator\Desktop";
            fileDialog.Title = "加载";
            fileDialog.Filter = "xls files (*.xls)|*.xls";
            fileDialog.FilterIndex = 1;
            fileDialog.RestoreDirectory = true;
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = fileDialog.FileName;
            }
            else
            {
                MessageBox.Show("没有选择任何文件");
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                string excelsql = string.Empty;
                string CarNum = string.Empty;
                string Tare = string.Empty;
                string t_name = string.Empty;
                string dengji = string.Empty;
                string shebeihao = string.Empty;
                string weizhi = string.Empty;
                string ask_time = string.Empty;
                string leixing = string.Empty;
                string conn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + textBox1.Text + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                OleDbConnection oleCon = new OleDbConnection(conn);
                oleCon.Open();
                string Sql = "select * from [Sheet1$]";
                OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, oleCon);
                DataSet ds = new DataSet();
                mycommand.Fill(ds, "[Sheet1$]");
                oleCon.Close();
                int count = ds.Tables["[Sheet1$]"].Rows.Count;
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        CarNum = ds.Tables["[Sheet1$]"].Rows[i]["部门"].ToString().Trim();
                        Tare = ds.Tables["[Sheet1$]"].Rows[i]["编号"].ToString().Trim();
                        t_name = ds.Tables["[Sheet1$]"].Rows[i]["姓名"].ToString().Trim();
                        dengji = ds.Tables["[Sheet1$]"].Rows[i]["登记号码"].ToString().Trim();
                        shebeihao = ds.Tables["[Sheet1$]"].Rows[i]["设备号"].ToString().Trim();
                        weizhi = ds.Tables["[Sheet1$]"].Rows[i]["位置"].ToString().Trim();
                        ask_time = ds.Tables["[Sheet1$]"].Rows[i]["签到时间"].ToString().Trim();
                        leixing = ds.Tables["[Sheet1$]"].Rows[i]["考勤类型"].ToString().Trim();
                        string findExit = "select * from kaoqin where CarNum='" + CarNum + "' and t_name = '" + t_name + "' and ask_time = '" + ask_time + "' and leixing = '" + leixing + "'";
                        DataTable dt = common.GetDataTable(findExit);//返回连接字符串          //选择ini
                        //DataTable dt = common.select("select * from kaoqin where CarNum='" + CarNum + "' and t_name = '" + t_name + "'");//自己写的
                        if (dt.Rows.Count > 0)
                        {
                            //MessageBox.Show("update kaoqin set Tare='" + Tare + "',t_name = '" + t_name + "',dengji = '"+dengji+"',shebeihao = '"+shebeihao+"',weizhi = '"+weizhi+"',ask_time = '" + ask_time + "',leixing = '"+leixing+"' where CarNum='" + CarNum + "'");
                            excelsql = string.Format("update kaoqin set Tare='" + Tare + "',t_name = '" + t_name + "',dengji = '" + dengji + "',shebeihao = '" + shebeihao + "',weizhi = '" + weizhi + "',ask_time = '" + ask_time + "',leixing = '" + leixing + "' where CarNum='" + CarNum + "' and t_name = '" + t_name + "' and ask_time = '" + ask_time + "' and leixing ='" + leixing + "'");
                        }
                        else
                        {
                            //MessageBox.Show("insert into kaoqin (CarNum, Tare,t_name,ask_time) values ('" + CarNum + "','" + Tare + "','" + t_name + "','" + ask_time + "')");
                            excelsql = string.Format("insert into kaoqin (CarNum,Tare,t_name,dengji,shebeihao,weizhi,ask_time,leixing) values ('" + CarNum + "','" + Tare + "','" + t_name + "','" + dengji + "','" + shebeihao + "','" + weizhi + "','" + ask_time + "','" + leixing + "')");
                        }
                        common.PostModify(excelsql);
                    }
                    MessageBox.Show("导入数据成功!");
                    //加载数据到datagridview
                    SqlConnection vconn = new SqlConnection(common.GetConnStr());
                    SqlDataAdapter sdp = new SqlDataAdapter("select * from kaoqin", vconn);
                    sdp.Fill(ds, "kaoqin");
                    dataGridView1.DataSource = ds.Tables[0];
                    vconn.Close();
                }
                catch
                {
                    MessageBox.Show("导入数据失败!");
                }
            }
            else
            {
                MessageBox.Show("路径为空");
            }
        }
        public void SaveAs(DataGridView dgvAgeWeekSex) //另存新档按钮导出成Excel
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.InitialDirectory = @"C:\Users\Administrator\Desktop\";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File To";
            //saveFileDialog.ShowDialog();
            Stream myStream;
            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string str = "";
                try
                {
                    //写标题
                    for (int i = 0; i < dgvAgeWeekSex.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dgvAgeWeekSex.Columns[i].HeaderText;
                    }
                    sw.WriteLine(str);
                    //写内容
                    for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)
                    {
                        //MessageBox.Show(dgvAgeWeekSex.Rows.Count.ToString());
                        string tempStr = "";
                        for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++)
                        {
                            //MessageBox.Show(dgvAgeWeekSex.Columns.Count.ToString());
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            if (dgvAgeWeekSex.Rows[j].Cells[k].Value != null)
                            {
                                tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString();
                            }
                        }
                        sw.WriteLine(tempStr);
                    }
                    sw.Close();
                    myStream.Close();
                    MessageBox.Show("导出成功");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
          dataGridView1.DataSource = common.myselect("select * from kaoqin").Tables[0];
          //加上 就是打印 全部数据 ,不加则 只打印 当前显示了的数据,因为 弄了分页效果 所以 要区分一下
          SaveAs(dataGridView1);
        }
    }
}



备注:由于书写匆忙 如果瑕疵 敬请指出(http://sdbzwh.blog.51cto.com/) 此文仅供参考

你可能感兴趣的:(C#,datagridview,导入导出EXECL)