2017-08-14 108 views
-3

我找不到在C#中使用ADO.Net连接导入和导出Excel数据到SQL服务器的方式我尝试此代码导出,但它不起作用,我不能发现,在计算机中的文件:如何导入和导出excel到SQL Server

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文件任何一个可以帮我这个以简单的方式

+0

为文件名中的另存为方法规定:文件名 要保存的文件的名称。您可以包含完整路径;如果您不这样做,Microsoft Office Excel会将该文件保存在当前文件夹中。 - 你在哪里告诉它要保存在你建议的位置?搜索你的项目文件,你可能会在那里创建它。 – Leonidas199x

回答

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 
      } 
     } 
+0

我应该添加这个代码? –

+0

那么你想调用它,如果是我,我会创建一个帮助类,并从任何你想要的地方调用你的方法 –

+0

我应该从PC选择文件,所以我添加打开对话框来选择文件,并使一个按钮选择它这是按钮的代码,我可以如何发送文件到这个方法 'OpenFileDialog op = new OpenFileDialog(); op.Filter =“Excel文件| * .xls; * xlsx; * xlsm”; if(op.ShowDialog()== DialogResult.Cancel) return; FileStream stream = new FileStream(op.FileName,FileMode.Open); IExcelDataReader excelreader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet结果= excelreader.AsDataSet();' –

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; 
       } 
      } 
     }