如何导入和导出Excel到SQL Server

时间:2017-08-14 11:31:23

标签: c# sql-server excel ado.net

我找不到使用ADO.Net连接将Excel数据导入和导出到C#中的SQL服务器的方法我尝试使用此代码导出但是它没有工作我无法找到计算机中的文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;

namespace ImportAndExport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn;
            string connectionString = null;
            string sql = null;
            string data = null;
            int i = 0;
            int j = 0;
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            connectionString = "data source=DESKTOP-I5MGTGH\\SQLEXPRESS;initial catalog=dbStkMaamoonKhalidIssue;Integrated Security=True;Trusted_Connection=True;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = "SELECT * FROM Person";
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet ds = new DataSet();
            dscmd.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                    xlWorkSheet.Cells[i + 1, j + 1] = data;
                }
            }

            xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Excel file created , you can find the file E:\\Abd El-Rahman\\csharp.net-informations.xls");

        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

最后的消息显示给我,但我在我的电脑上搜索但是我无法找到我的excel文件,任何人都可以轻松地帮助我这个

2 个答案:

答案 0 :(得分:0)

确保您的数据与您在SQL Server中创建的数据类型相匹配。

using System.Data.OleDb; 
using System.Data.SqlClient;

SQL

 SET ANSI_NULLS ON 
    GO 
    SET QUOTED_IDENTIFIER ON 
    GO 
    SET ANSI_PADDING ON 
    GO 
    CREATE TABLE [dbo].[Table1]( 
        [student] [varchar](50) NULL, 
        [rollno] [int] NULL, 
        [course] [varchar](50) NULL 
    ) ON [PRIMARY] 
    GO 
    SET ANSI_PADDING OFF 
    GO 

C#

 public void ImportDataFromExcel(string excelFilePath) 
        { 
            //declare variables - edit these based on your particular situation 
            string ssqltable = "Table1"; 
            // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have    different 
            string myexceldataquery = "select student,rollno,course from [Sheet1$]"; 
            try 

            { 
                //create our connection strings 
                string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath + 
                ";extended properties=" + "\"excel 8.0;hdr=yes;\""; 
                string ssqlconnectionstring = "Data Source=SAYYED;Initial Catalog=SyncDB;Integrated Security=True"; 
                //execute a query to erase any previous data from our destination table 
                string sclearsql = "delete from " + ssqltable; 
                SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring); 
                SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn); 
                sqlconn.Open(); 
                sqlcmd.ExecuteNonQuery(); 
                sqlconn.Close(); 
                //series of commands to bulk copy data from the excel file into our sql table 
                OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring); 
                OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn); 
                oledbconn.Open(); 
                OleDbDataReader dr = oledbcmd.ExecuteReader(); 
                SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring); 
                bulkcopy.DestinationTableName = ssqltable; 
                while (dr.Read()) 
                { 
                    bulkcopy.WriteToServer(dr); 
                } 
                dr.Close(); 
                oledbconn.Close(); 
                Label1.Text = "File imported into sql server."; 
            } 
            catch (Exception ex) 
            { 
                //handle exception 
            } 
        }

答案 1 :(得分:0)

这似乎是一个非常通用的问题。通常,此网站最适用于您无法找到解决方案的非常专业的问题,即使在进行多次Google搜索之后也是如此。至少,这就是我的想法。

从SQL SERVER导出到EXCEL:

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn ;
            string connectionString = null;
            string sql = null;
            string data = null;
            int i = 0;
            int j = 0; 

            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = "SELECT * FROM Product";
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet ds = new DataSet();
            dscmd.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                    xlWorkSheet.Cells[i + 1, j + 1] = data;
                }
            }

            xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

    }
}

另外。 。

从EXCEL导出到SQL SERVER:

// if you have Excel 2007 uncomment this line of code 
        //  string excelConnectionString =string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0",path); 

        string ExcelContentType = "application/vnd.ms-excel"; 
        string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
        if (FileUpload1.HasFile) 
        { 
            //Check the Content Type of the file 
            if(FileUpload1.PostedFile.ContentType==ExcelContentType || FileUpload1.PostedFile.ContentType==Excel2010ContentType) 
            { 
                try 
                { 
                    //Save file path 
                    string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName); 
                    //Save File as Temp then you can delete it if you want 
                    FileUpload1.SaveAs(path); 
                    //string path = @"C:\Users\Johnney\Desktop\ExcelData.xls"; 
                    //For Office Excel 2010  please take a look to the followng link  http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/0f03c2de-3ee2-475f-b6a2-f4efb97de302/#ae1e6748-297d-4c6e-8f1e-8108f438e62e 
                    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path); 

                    // Create Connection to Excel Workbook 
                    using (OleDbConnection connection = 
                                 new OleDbConnection(excelConnectionString)) 
                    { 
                        OleDbCommand command = new OleDbCommand 
                                ("Select * FROM [Sheet1$]", connection); 

                        connection.Open(); 

                        // Create DbDataReader to Data Worksheet 
                        using (DbDataReader dr = command.ExecuteReader()) 
                        { 

                            // SQL Server Connection String 
                            string sqlConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"; 

                            // Bulk Copy to SQL Server 
                            using (SqlBulkCopy bulkCopy = 
                                       new SqlBulkCopy(sqlConnectionString)) 
                            { 
                                bulkCopy.DestinationTableName = "Employee"; 
                                bulkCopy.WriteToServer(dr); 
                                Label1.Text = "The data has been exported succefuly from Excel to SQL"; 
                            } 
                        } 
                    } 
                } 

                catch (Exception ex) 
                { 
                    Label1.Text = ex.Message; 
                } 
            } 
        }