Uploading an Excel sheet and importing the data into SQL Server database

前端 未结 9 1661
闹比i
闹比i 2020-11-29 01:08

I am developing this simple application to upload an Excel file (.xlsx) and import the data present in that Excel worksheet into a SQL Server Express database i

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:02

    You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)

    Example:

    private static void DataReaderBulkCopySample()
    {            
        using (var reader = new ExcelDataReader(@"test.xlsx"))
        {
            var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
            DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
    
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {
                // MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess, 
                // optimizing memory usage by using the IDataReader streaming capabilities
                bulkCopy.EnableStreaming = true;
    
                bulkCopy.DestinationTableName = TableName;
                foreach (var col in cols)
                    bulkCopy.ColumnMappings.Add(col, col);
    
                bulkCopy.WriteToServer(reader);
            }
        }
    }
    

提交回复
热议问题