Excel2003,2007,2010,2013导入导出sqlserver

5 篇文章 0 订阅
0 篇文章 0 订阅

添加Microsoft.Office.Interop.Excel引用。

ExcelIO类:

using System;
using System.Data;
using System.Data.OleDb;
//using System.Collections.Generic;
//using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Collections;

namespace com.Common.Utility
{
    ///
    //Purpose:Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library 
    //Author: Dangmy 
    //Date: 2007-03-09
    //Version: 1.0
    /// 
    public class ExcelIO
    {
        private int _ReturnStatus;
        private string _ReturnMessage;

        public ExcelIO()
        {
        }

        /// <summary>
        /// 执行返回状态
        /// </summary>
        public int ReturnStatus
        {
            get { return _ReturnStatus; }
        }

        /// <summary>
        /// 执行返回信息
        /// </summary>
        public string ReturnMessage
        {
            get { return _ReturnMessage; }
        }

        /// <summary>
        /// 导入EXCEL文件到DataSet
        /// </summary>
        /// <param name="fileName">Excel全路径文件名</param>
        /// <returns>导入成功的DataSet</returns>
        public DataSet SubImportExcel(string fileName)
        {
            //判断是否安装EXCEL
            Excel.Application xlApp = new Excel.Application();
            if (xlApp == null)
            {
                _ReturnStatus = -1;
                _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
                return null;
            }

            //判断文件是否被其他进程使用            
            Excel.Workbook workbook;
            try
            {
                workbook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
            }
            catch
            {
                _ReturnStatus = -1;
                _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
                return null;
            }

            //获得所有Sheet名称
            int n = workbook.Worksheets.Count;
            string[] SheetSet = new string[n];
            //System.Collections.ArrayList al = new System.Collections.ArrayList();
            for (int i = 1; i <= n; i++)
            {
                SheetSet[i - 1] = ((Excel.Worksheet)workbook.Worksheets[i]).Name;
            }

            //释放Excel相关对象
            workbook.Close(null, null, null);
            xlApp.Quit();
            if (workbook != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
            }
            if (xlApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlApp = null;
            }
            GC.Collect();

            string strEName = fileName.Substring(fileName.LastIndexOf(".") + 1, (fileName.Length - fileName.LastIndexOf(".") - 1));

            //把EXCEL导入到DataSet
            DataSet ds = new DataSet();
            string connStr = string.Empty;

            if (strEName == "xls")
            {
                connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + fileName + ";Extended Properties='Excel 8.0;HDR=YES'";
            }
            else if (strEName == "xlsx")
            {
                connStr = " Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source= " + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
            }
            else
            {
                return null;
            }

            using (OleDbConnection conn = new OleDbConnection(connStr))
            {
                conn.Open();
                OleDbDataAdapter da;
                for (int i = 1; i <= n; i++)
                {
                    string sql = "select * from [" + SheetSet[i - 1] + "$] ";
                    da = new OleDbDataAdapter(sql, conn);
                    da.Fill(ds, SheetSet[i - 1]);
                    da.Dispose();
                }
                conn.Close();
                conn.Dispose();
            }
            return ds;
        }

        /// <summary>
        /// 把Excel导入到DataSet
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public DataSet SubImportExcel(string fileName, string[] SheetName)
        {
            //判断是否安装EXCEL
            Excel.Application xlApp = new Excel.Application();
            if (xlApp == null)
            {
                _ReturnStatus = -1;
                _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
                return null;
            }

            //判断文件是否被其他进程使用            
            Excel.Workbook workbook;
            try
            {
                workbook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
            }
            catch
            {
                _ReturnStatus = -1;
                _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
                return null;
            }

            //获得所有Sheet名称
            int n = workbook.Worksheets.Count;
            string[] SheetSet = new string[n];
            for (int i = 1; i <= n; i++)
            {
                SheetSet[i - 1] = ((Excel.Worksheet)workbook.Worksheets[i]).Name;
            }

            //释放Excel相关对象
            workbook.Close(null, null, null);
            xlApp.Quit();
            if (workbook != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
            }
            if (xlApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlApp = null;
            }
            GC.Collect();

            bool bolSheet = true;
            for (int i = 0; i < SheetName.Length; i++)
            {
                if (!((IList)SheetSet).Contains(SheetName[i]))
                {
                    bolSheet = false;
                }
            }

            if (bolSheet)
            {
                string strEName = fileName.Substring(fileName.LastIndexOf(".") + 1, (fileName.Length - fileName.LastIndexOf(".") - 1));

                //把EXCEL导入到DataSet
                DataSet ds = new DataSet();
                string connStr = string.Empty;

                if (strEName == "xls")
                {
                    connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + fileName + ";Extended Properties='Excel 8.0;HDR=YES'";
                }
                else if (strEName == "xlsx")
                {
                    connStr = " Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source= " + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
                }
                else
                {
                    return null;
                }

                using (OleDbConnection conn = new OleDbConnection(connStr))
                {
                    conn.Open();
                    OleDbDataAdapter da;
                    for (int i = 0; i < SheetName.Length; i++)
                    {
                        string sql = "SELECT * FROM [" + SheetName[i] + "$]";
                        da = new OleDbDataAdapter(sql, conn);
                        da.Fill(ds, SheetName[i]);
                        da.Dispose();
                    }
                    conn.Close();
                    conn.Dispose();
                }
                return ds;
            }
            else
            {
                _ReturnStatus = -1;
                _ReturnMessage = "Excel文件不存在制定名称的Sheet";
                return null;
            }
        }

        /// <summary>
        /// 把DataTable导出到EXCEL
        /// </summary>
        /// <param name="reportName">报表名称</param>
        /// <param name="dt">数据源表</param>
        /// <param name="saveFileName">Excel全路径文件名</param>
        /// <returns>导出是否成功</returns>
        public bool SubExportExcel(string reportName, System.Data.DataTable dt, string saveFileName)
        {
            if (dt == null | dt.Rows.Count == 0)
            {
                _ReturnStatus = -1;
                _ReturnMessage = "数据集为空!";
                return false;
            }
            bool fileSaved = false;

            //保存文件
            if (saveFileName != "")
            {
                DateTime Process_BeforeTime = DateTime.Now;
                Excel.Application xlApp = new Excel.Application();
                DateTime Process_AfterTime = DateTime.Now;
                if (xlApp == null)
                {
                    _ReturnStatus = -1;
                    _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
                    return false;
                }

                Excel.Workbooks workbooks = xlApp.Workbooks;
                Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
                Excel.Range range;

                worksheet.Cells.Font.Size = 10;

                long totalCount = dt.Rows.Count;
                long rowRead = 0;
                float percent = 0;

                worksheet.Cells.NumberFormatLocal = "@";
                worksheet.Cells[1, 1] = reportName;
                ((Excel.Range)worksheet.Cells[1, 1]).Font.Size = 12;
                ((Excel.Range)worksheet.Cells[1, 1]).Font.Bold = true;

                //写入字段
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
                    range = (Excel.Range)worksheet.Cells[2, i + 1];
                    range.Interior.ColorIndex = 15;
                    range.Font.Bold = true;

                }
                //写入数值
                for (int r = 0; r < dt.Rows.Count; r++)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
                    }
                    rowRead++;
                    percent = ((float)(100 * rowRead)) / totalCount;
                }

                range = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]);
                range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);

                if (dt.Rows.Count > 0)
                {
                    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
                    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
                    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
                }

                if (dt.Columns.Count > 1)
                {
                    range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
                    range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
                    range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
                }

                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    _ReturnStatus = -1;
                    _ReturnMessage = "导出文件时出错,文件可能正被打开!\n" + ex.Message;
                    
                    //WriteInfoToTxt.WriteErrorLog("导出excel" + _ReturnMessage);
                }
                finally
                {
                    //释放Excel对应的对象
                    workbook.Close(Type.Missing, Type.Missing, Type.Missing);

                    if (xlApp != null)
                    {
                        xlApp.Application.Quit();
                        xlApp.Quit();
                    }


                    if (workbook != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                        workbook = null;
                    }

                    if (workbooks != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
                        workbooks = null;
                    }

                    if (xlApp != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                        xlApp = null;
                    }





                    KillExcelProcess(Process_BeforeTime, Process_AfterTime);

                    GC.Collect();
                }
            }
            else
            {
                fileSaved = false;
            }

            return fileSaved;
        }

        public bool ExportExcel(string reportName, System.Data.DataTable dt, string saveFileName)
        {
            bool flag = false;
            if (SubExportExcel(reportName, dt, saveFileName))
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
            GC.Collect();
            return flag;
        }

        public DataSet ImportExcel(string fileName)
        {
            DataSet ds = SubImportExcel(fileName);
            GC.Collect();
            return ds;
        }

        /// <summary>
        /// 关闭当前Excel进程 
        /// </summary>
        /// <param name="Process_BeforeTime"></param>
        /// <param name="Process_AfterTime"></param>
        public static void KillExcelProcess(DateTime Process_BeforeTime, DateTime Process_AfterTime)
        {
            foreach (Process pro in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
            {
                DateTime ProcessBeginTime = pro.StartTime;
                if ((ProcessBeginTime >= Process_BeforeTime) && (ProcessBeginTime <= Process_AfterTime))
                {
                    pro.Kill();
                }
            }
        }

        /// <summary>
        /// 在当前工作表中根据数据生成图表:CreateChart(m_Book, m_Sheet, num); 
        /// </summary>
        /// <param name="m_Book"></param>
        /// <param name="m_Sheet"></param>
        /// <param name="num"></param>
        //private void CreateChart(Excel._Workbook m_Book, Excel._Worksheet m_Sheet, Excel.Range oResizeRange)
        private void CreateChart(Excel._Workbook m_Book, Excel._Worksheet m_Sheet, int num)
        {
            Excel.Range oResizeRange;
            Excel.Series oSeries;
            m_Book.Charts.Add(Missing.Value, Missing.Value, 1, Missing.Value);

            m_Book.ActiveChart.ChartType = Excel.XlChartType.xlLine;//设置图形

            //设置数据取值范围
            m_Book.ActiveChart.SetSourceData(m_Sheet.get_Range("A3", "C" + (num + 1).ToString()), Excel.XlRowCol.xlColumns);
            //m_Book.ActiveChart.Location(Excel.XlChartLocation.xlLocationAutomatic, title);
            //以下是给图表放在指定位置
            m_Book.ActiveChart.Location(Excel.XlChartLocation.xlLocationAsObject, m_Sheet.Name);
            oResizeRange = (Excel.Range)m_Sheet.Rows.get_Item(10, Missing.Value);
            m_Sheet.Shapes.Item(0).Top = (float)(double)oResizeRange.Top;  //调图表的位置上边距
            oResizeRange = (Excel.Range)m_Sheet.Columns.get_Item(6, Missing.Value);  //调图表的位置左边距
            // m_Sheet.Shapes.Item(0).Left = (float)(double)oResizeRange.Left;
            if (num <= 30)
            {
                m_Sheet.Shapes.Item(0).Width = 600;
            }
            else
            {
                m_Sheet.Shapes.Item(0).Width = 20 * num;   //调图表的宽度
            }
            m_Sheet.Shapes.Item(0).Height = 250;  //调图表的高度

            m_Book.ActiveChart.PlotArea.Interior.ColorIndex = 19;  //设置绘图区的背景色 
            m_Book.ActiveChart.PlotArea.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置绘图区边框线条
            if (num <= 30)
            {
                m_Book.ActiveChart.PlotArea.Width = 600;
            }
            else
            {
                m_Book.ActiveChart.PlotArea.Width = 20 * num;   //设置绘图区宽度
            }
            //m_Book.ActiveChart.ChartArea.Interior.ColorIndex = 10; //设置整个图表的背影颜色
            //m_Book.ActiveChart.ChartArea.Border.ColorIndex = 8;// 设置整个图表的边框颜色
            m_Book.ActiveChart.ChartArea.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置边框线条
            m_Book.ActiveChart.HasDataTable = false;

            //设置Legend图例的位置和格式
            m_Book.ActiveChart.Legend.Top = 20.00; //具体设置图例的上边距
            m_Book.ActiveChart.Legend.Left = 60.00;//具体设置图例的左边距
            m_Book.ActiveChart.Legend.Interior.ColorIndex = Excel.XlColorIndex.xlColorIndexNone;
            m_Book.ActiveChart.Legend.Width = 150;
            m_Book.ActiveChart.Legend.Font.Size = 9.5;
            //m_Book.ActiveChart.Legend.Font.Bold = true;
            m_Book.ActiveChart.Legend.Font.Name = "宋体";
            //m_Book.ActiveChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;//设置图例的位置
            m_Book.ActiveChart.Legend.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置图例边框线条

            //设置X轴的显示
            Excel.Axis xAxis = (Excel.Axis)m_Book.ActiveChart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
            xAxis.MajorGridlines.Border.LineStyle = Excel.XlLineStyle.xlDot;
            xAxis.MajorGridlines.Border.ColorIndex = 1;//gridLine横向线条的颜色
            xAxis.HasTitle = false;
            xAxis.TickLabels.Font.Name = "宋体";
            xAxis.TickLabels.Font.Size = 9;

            //            .NumberFormatLocal = "0_ "
            //设置Y轴的显示
            Excel.Axis yAxis = (Excel.Axis)m_Book.ActiveChart.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
            yAxis.TickLabelSpacing = 30;
            //yAxis.TickLabels.NumberFormat = "M月D日";
            //yAxis.MaximumScaleIsAuto = true;
            //yAxis.MinimumScaleIsAuto = true;

            yAxis.TickLabels.Orientation = Excel.XlTickLabelOrientation.xlTickLabelOrientationHorizontal;//Y轴显示的方向,是水平还是垂直等
            yAxis.TickLabels.Font.Size = 8;
            yAxis.TickLabels.Font.Name = "宋体";
            //m_Book.ActiveChart.Floor.Interior.ColorIndex = 8;  
            /***以下是设置标题*****
            m_Book.ActiveChart.HasTitle=true;
            m_Book.ActiveChart.ChartTitle.Text = "净值指数";
            m_Book.ActiveChart.ChartTitle.Shadow = true;
            m_Book.ActiveChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;
            */
            oSeries = (Excel.Series)m_Book.ActiveChart.SeriesCollection(1);
            oSeries.Name = "在线数";
            oSeries.Values = "='" + m_Sheet.Name + "'!$C$3:$C$" + (num + 1).ToString();
            oSeries.XValues = "='" + m_Sheet.Name + "'!$A$3:$B$" + (num + 1).ToString();
            oSeries.Border.ColorIndex = 45;
            oSeries.Border.Weight = Excel.XlBorderWeight.xlThick;
            //oSeries = (Excel.Series)m_Book.ActiveChart.SeriesCollection(2);
            //oSeries.Border.ColorIndex = 9;
            //oSeries.Border.Weight = Excel.XlBorderWeight.xlThick;

        }


    }
}

Winform窗体事件:

 private void button1_Click_1(object sender, EventArgs e)
        {
            string path = "";
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                path = Path.GetFullPath(ofd.FileName);
            }
            ExcelIO exio = new ExcelIO();
            DataSet ds = exio.SubImportExcel(path);
            this.dataGridView1.DataSource = ds.Tables[0];
            InsertToSql(ds.Tables[0]);
        }
        private void InsertToSql(DataTable dt)
        {

            string connString = Properties.Settings.Default.StudentAttendenceConnectionString;
            SqlParameter[] sqlpars = null;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sqlpars = new SqlParameter[6];
                sqlpars[0] = new SqlParameter("@StudentNumber", dt.Rows[i].ItemArray[0].ToString());
                sqlpars[1] = new SqlParameter("@StudentID", dt.Rows[i].ItemArray[1].ToString());
                sqlpars[2] = new SqlParameter("@ClassID",Int32.Parse(dt.Rows[i].ItemArray[2].ToString()));
                sqlpars[3] = new SqlParameter("@StudentName", dt.Rows[i].ItemArray[3].ToString());
                sqlpars[4] = new SqlParameter("@StudentGender", dt.Rows[i].ItemArray[4].ToString());
                sqlpars[5] = new SqlParameter("@StudentPhoto", dt.Rows[i].ItemArray[5].ToString());

               
                int row =RunProcedureForUpdate("InsertIntoStudentInfo", sqlpars,connString);
                if (row == 0)
                {
                    MessageBox.Show("导入失败");
                }
                else
                {
                    MessageBox.Show("导入成功");
                }
            }
        }
/// <summary>
        /// 更新--执行存储过程,返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns></returns>
        private int RunProcedureForUpdate(string storedProcName, IDataParameter[] parameters,string strCon)
        {
            using (SqlConnection connection = new SqlConnection(strCon))
            {
                int rowsAffected = 0;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.ToString());
                }
                return rowsAffected;
            }
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private  SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

最后如果提示导入成功但未更新到数据库,将Program.cs的main函数中添加

static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string dataDir = AppDomain.CurrentDomain.BaseDirectory;
          if (dataDir.EndsWith(@"\bin\Debug\")|| dataDir.EndsWith(@"\bin\Release\"))
          {
              dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
              AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
          }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Office数据库升迁 Access 导入 SQL Server,相信大家都知道 SQL-Server 数据库导入导出功能吧,但当你装了精简版的SQL-Server这个功能就会没有了,也就是无法实现数据库导入导出,那么怎么办 写SQL语句? Insert into Tables SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source="E:\Access.mdb";') 显然在正常情况下这可以 但如果你看见提示 Msg 15281, Level 16, State 1, Line 1 SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online. 这时怎么办? EXEC sp_configure 'show advanced options', 1 EXEC sp_configure 'Ad Hoc Distributed Queries', 1 结果你又被提示: Msg 15123, Level 16, State 1, Procedure sp_configure, Line 51 The configuration option 'Ad Hoc Distributed Queries' does not exist, or it may be an advanced option. 很明确这条路是走不通了,因为精简版的SQL-Server没这功能。所以你就要用的我的资源了。这里主要是通过Access自带功能(你要安装这个,暂时叫插件吧)完成数据库转换。 步骤: 1.打开Access 点击菜单栏中的--》工具 2.打开 工具栏下的--》数据库实用工具 3.选择 升迁向导(和SQL导入那里一样了 相当于数据库导出 ) 选择你的 SQL-Server 服务器地址,登陆账号和密码,同时填写 生成后的SQL-Server数据库名称,就这样简单完成了。Access到SQL-Server的转换。 Ps:当然你装的是完整版的SQL-Server, 直接可以导入导出(语句也可以的),不用这样麻烦,但如果你装的就是SQL-Server精简版那么这或许是最后的方法,同时也是对Access转SQL-Server有一个新的认识。 文件包: PRO11.MSI,A4561414.CAB,CR561401.CAB,MA561416.CAB,PA561401.CAB,SKU011.CAB,YI561401.CAB,YS561409.CAB,ZA561401.CAB, ZD561403.CAB,ZU561415.CAB,ZZ561401.CAB(office2003的) 我也是因为遇见这问题,才按这个方法成功的。希望对大家都帮助
[SQL]将Excel表数据导入SQL Server2005的几种方法归纳 数据库 2010-07-27 11:14:26 阅读201 评论0 字号:大中小 订阅 近日在巨轮着手车间负荷数据处理,反馈回来的数据是保存在Excel文件中的,我必须将其导入SQL Server2005中,供存储过程计算。 由于之前没有将Excel数据导入SQL Server2005的经验,因此摸索着花了一天时间才搞定。下面将网上收集到的几种导入方法做个归纳。 方法一、利用SQL Server2005自带的DTS工具,手工导入: 第一步是点击开始并选择运行并输入CMD然后在命令提示符里输入DTSWIZARD。SQL Server 导入导出向导的欢迎界面将显示出来,如下图所示:(也可以这样打开该界面:1、登录到 SQL Server Management Studio。2、在 “对象资源管理器 ”中右键单击 “管理 ”,在弹出列表中单击 “导入数据 ”。)   当你点击下一步按钮时,它将进入选择数据源向导界面。用户应该选择数据源为Microsoft Office 12.0 Access Database Engine OLE DB Provider 然后在向导界面中点击属性…按钮,它将弹出数据链接属性界面。在所有标签页中,双击数据源属性值并输入电子数据表的位置,例如“C:\Excel2007\Import\SampleData.xlsx”作为导入数据的数据源的Microsoft Office Excel 2007文件名称和路径。然后双击扩展属性并选择Excel 12.0作为属性值。   到Microsoft Office Excel 2007的连接可以通过点击测试连接按钮来进行测试,如下图所示:   在下一个页面中,数据源需要选为SQL Native Client,因为数据将导入SQL Server 2005。然后你需要选择数据所要导入的服务器名称,并需要配置合适的验证模式,它之后跟着数据库名称。  在这个例子中,我们将使用windows验证连接到本地SQL Server实例,所使用的数据库将是ImportExcel。   在Specify Table Copy or Query(指定表复制或查询)向导界面中,选择copy data from one or more tables or views(从一个或多个表或视图复制数据)选项,并继续这个向导到下一个界面。   在Select Source Table and Views(选择源表和视图)向导界面中,用户需要在源中选择雇员电子数据表,然后在目标中就可以看到ImportExcel.dbo.Employee了。之后点击Edit Mappings…(编辑匹配…),扫描电子数据表中的可用数据,如果数据类型与SQL Server所建议的不同的话那么指定数据类型。   在Save and Execute Package(保存和执行包)向导界面中,有两个选项叫做Execute Immediately(立即执行)和Save SSIS Package as file system(保存SSIS包为文件系统)。你可以选择任何一个选项然后点击Finish(完成)按钮来运行和结束这个包配置。 方法二、在查询分析器里,直接写 SQL语句: 1、如果是导入数据到现有表,则采用 INSERT INTO 表 SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$) 的形式 2、如果是导入数据并新增表,则采用 SELECT * INTO 表 FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$) 的形式。 以上语句是将 EXCEL文件里 SHEET1工作表中所有的列都读进来,如果只想导部分列,可以 INSERT INTO 表 (a1,a2,a3) SELECT a1,a2,a3 FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$) 其实可以将 OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)当成一个表,例如我就写过这样一个句子: INSERT INTO eval_channel_employee(channel,employee_id) SELECT CASE a.渠道 WHEN 'DIY' THEN 1 WHEN 'RDC' THEN 0 WHEN 'KCM' THEN 2 ELSE 3 END ,b.id FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=c:\temp\name.xls',sheet1$) AS a,pers_employee b WHERE a.员工编码 =b.code 不管是哪种方式,哪种途径,系统都会默认将第一行上的内容作为字段名。 3、利用C#自己开发数据导入小工具 //连接串 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + [EXCEL文件,含路径] + ";"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[] {null, null, null, "TABLE"}); DataSet ds = new DataSet(); //一个EXCEL文件可能有多个工作表,遍历之 foreach( DataRow dr in dtSchema.Rows ) { string table = dr["TABLE_NAME"].ToString(); string strExcel = "SELECT * FROM [" + table + "]"; ds.Tables.Add(table); OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel,conn); myCommand.Fill(ds,table); } conn.Close(); 这样,读取出来的数据就藏在 DataSet里了。 采用这种方式,数据库所在机器不必装有 EXCEL。 总结: 当Excel表中数据完整时,利用SQL自带的导入工具手工导入比较方便。当数据不完整或数据格式对应不上时,使用导入工具会出错,利用SQL查询语句就更便捷。当结合以上两种方法的优点,利用C#自己开发出数据导入工具是最佳选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值