• Excel导入导出数据库


      有时候我们会遇到这样的需求,需要向数据库导入Excel,或者从数据库中导出数据存为Excel,尤其是在做报表的时候,或者需要从其他系统导入数据,一般都是以Excel文件形式存在的。正好这几天在做这样的事,我整理一下这两种操作的大概做法。以后遇到这样的问题就不用怕了!!!

    1.数据从数据库中导出存为Excel:

     private void btnInput_Click(object sender, EventArgs e)
            {
                DataGridViewToExcel("采集信息");
            }
     
            private void DataGridViewToExcel( string filename)
            {
                using (OperationClient proxy = new OperationClient())//引用了服务代理
                {
                    try
                    {
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.Filter = "Execl files (*.xls)|*.xls";
                        dlg.FilterIndex = 0;
                        dlg.RestoreDirectory = true;
                        dlg.Title = "保存为Excel文件";
                        dlg.FileName = filename;
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            Stream myStream;
                            myStream = dlg.OpenFile();
                            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                            string colHeaders = "", ls_item = "";
                            //写入列标题    
                            colHeaders += "身份证号" + "	";
                            colHeaders += "是否采集";
                            sw.WriteLine(colHeaders);
                            //写入列内容
                            //这里的proxy.Output()函数是调用定义好的WCF服务中的,它返回值是一个集合,而每个元素都是一条记录(多个字段)
                            foreach (var s in proxy.Output())
                            {
                                ls_item += s.ID + "	";
                                ls_item += s.statu;
                                sw.WriteLine(ls_item);
                                ls_item = "";
                            }
                            sw.Close();
                            myStream.Close();
                            MessageBox.Show("导出[" + filename + "]成功""提示");
     
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

    2.Excel的数据导入到数据库中

    private void btnOutput_Click(object sender, EventArgs e)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "表格文件 (*.xls)|*.xls";
                openFileDialog.RestoreDirectory = true;
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    InExcelData(openFileDialog.FileName);
                }
                MessageBox.Show("导入[" + openFileDialog.FileName + "]成功""提示");
            }
             private bool InExcelData(string filePath)
            {
                try
                {
                    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;";
     
                    OleDbConnection con = new OleDbConnection(strConn);
                    con.Open();
                    string[] names = GetExcelSheetNames(con);//GetExcelSheetNames(filePath);
                    if (names != null)
                    {
                        if (names.Length > 0)
                        {
                            foreach (string name in names)
                            {
                                OleDbCommand cmd = con.CreateCommand();
                                cmd.CommandText = string.Format(" select * from [{0}]", name);//[sheetName$]要如此格式
                                OleDbDataReader odr = cmd.ExecuteReader();
     
                                while (odr.Read())
                                {
     
                                     if (odr[0].ToString() != "")
                                    {
                                        if (odr[0].ToString() == "身份证号")//过滤列头 按你的实际Excel文件
                                            continue;
                       //以下内容视自己的需要改动,要知道这里odr就是一个集合了,这里用循环是把集合里面每个元素读出来,一个元素就是一条记录(多个字段),
    //一般我们都会把一条记录定义成一个数据契约,方便传输                                       using (OperationClient proxy = new OperationClient())                                     {                                         Excel excel=new Excel(){ID = odr[0].ToString(),statu = odr[1].ToString()};                                         proxy.InExcels(excel); //服务那边定义成一个数据契约类型的集合,例如InExcels(Excel excel)                                    }                                 }                             }                             odr.Close();                                                      }                     }                 }                 con.Close();                 return true;                             }             catch (Exception ex)             {                 MessageBox.Show(ex.Message);                 return false;             }         }         public static string[] GetExcelSheetNames(OleDbConnection con)         {             try             {                 DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { nullnullnull"Table" });//检索Excel的架构信息                 var sheet = new string[dt.Rows.Count];                 for (int i = 0, j = dt.Rows.Count; i < j; i++)                 {                     sheet[i] = dt.Rows[i]["TABLE_NAME"].ToString();                 }                 return sheet;             }             catch             {                 return null;             }         }
  • 相关阅读:
    JAVA安卓和C# 3DES加密解密的兼容性问题(2013年8月修改版)
    eval绑定decimal数据后,如何去掉后面没有意义的0?
    Linq使用Group By经验总结
    mysql 分页存储过程 一次返回两个记录集(行的条数,以及行记录),DataReader的Read方法和NextResult方法
    把 HttpHandler.ashx 修改为 异步编程 异步操作
    td内容自动换行 ,td超过宽度显示点点点… , td 使用 overflow:hidden 无效,英文 数字 不换行 撑破div容器
    window.location.href = window.location.href 跳转无反应 a 超链接 onclick 点击跳转无反应
    C#怎么调用百度地图Web API
    .Net MVC 当前上下文中不存在名称“Style”
    无法使用备份文件 'D:20160512.bak',因为原先格式化该文件时所用扇区大小为 512,而目前所在设备的扇区大小为 4096
  • 原文地址:https://www.cnblogs.com/xushaoxin/p/3227442.html
Copyright © 2020-2023  润新知