简体   繁体   English

当我尝试使用 ExcelDataReader 将文件上传到数据库时出现“不支持指定的方法”错误

[英]I get a "Specified method is not supported" error when i try to use ExcelDataReader to upload file to database

I've written a method, BulkCopy, to upload my Excel file to SQL Server database table.我编写了一个方法 BulkCopy,将我的 Excel 文件上传到 SQL Server 数据库表。 I am trying to unit test this and it fails each time with "System.NotSupportedException : Specified method is not supported".我正在尝试对此进行单元测试,但每次都失败并显示“System.NotSupportedException:不支持指定的方法”。

If someone could have a look it would be much appreciated.如果有人可以看看,将不胜感激。

Kind regards,亲切的问候,

Emmett埃米特

    public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                    var column = cols.GetValue(0).ToString();

                    if (column.Trim() == "Column 1")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 1");
                    }

                    if (column.Trim() == "Column 2")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 2");
                    }

                    if (column.Trim() == "Column 3")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 3");
                    }

                //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }

I tested your code ,the issue is showed in the following code ,you reader is incorrect.我测试了您的代码,问题显示在以下代码中,您的阅读器不正确。

bulkCopy.WriteToServer(reader);

Pass the datatable into bulk , try the below code将数据表批量传递,试试下面的代码

public static void BulkCopy(string inputFilePath, string tableName)
    {
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = System.IO.File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        IExcelDataReader reader;

        if (inputFilePath.EndsWith(".xls"))
            reader = ExcelReaderFactory.CreateBinaryReader(stream);
        else if (inputFilePath.EndsWith(".xlsx"))
            reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        else
            throw new Exception("The file to be processed is not an Excel file");
        var conf = new ExcelDataSetConfiguration
        {
            ConfigureDataTable = _ => new ExcelDataTableConfiguration
            {
                UseHeaderRow = true
            }
        };
        var dataSet = reader.AsDataSet(conf);

        // Now you can get data from each sheet by its index or its "name"
        var dataTable = dataSet.Tables[0];

        using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {
                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                    var column =col.ToString();

                    if (column.Trim() == "Column 1")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column1");
                    }

                    if (column.Trim() == "Column 2")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column2");
                    }

                    if (column.Trim() == "Column 3")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column3");
                    }

                    //continued for column mappings...

                }
                bulkCopy.WriteToServer(dataTable);
            }
            Console.WriteLine("Copy data to database done (DataReader).");           
    }

Pass the dataReader into bulk , change your foreach part as shown将 dataReader 传入批量,如图所示更改foreach部分

               for (var i = 0; i<cols.Count();i++)
                {
                    if (cols[i].ToString().Trim() == "Column 1")
                    {
                        bulkCopy.ColumnMappings.Add(i, "Column1");
                    }

                    if (cols[i].ToString().Trim() == "Column 2")
                    {
                        bulkCopy.ColumnMappings.Add(i, "Column2");
                    }

                    if (cols[i].ToString().Trim() == "Column 3")
                    {
                        bulkCopy.ColumnMappings.Add(i, "Column3");
                    }

                    //continued for column mappings...

                }

You need to change the way it's setting the column mappings.您需要更改它设置列映射的方式。 If you delete them it will work.如果您删除它们,它将起作用。 In the example link you posted they are using GetName to get the columns.在您发布的示例链接中,他们使用GetName来获取列。 I tried that and it doesn't work for some reason.我试过了,但由于某种原因它不起作用。 I get a GetOrdinal error.我收到一个GetOrdinal错误。 That's the same error that is coming from your code: ExcelDataReader.ExcelDataReader`2.GetOrdinal(String name) .这与来自您的代码的错误相同: ExcelDataReader.ExcelDataReader`2.GetOrdinal(String name)

Not sure how pretty it is, but it works.不知道它有多漂亮,但它有效。

public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                     if (cols[i].ToString() == "Column 1")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 1");
                     }

                     if (cols[i].ToString() == "Column 2")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 2");
                     }

                     if (cols[i].ToString() == "Column 3")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 3");
                     }

                    //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试在Azure DataLake中写文件时,我得到了不支持的方法 - When I try to write on a file in Azure DataLake I get method not supported 我正在尝试创建一个上传文件按钮,但每当我尝试使用文件时,我都会收到错误“空路径名称不合法” - I am trying to create an upload file button, but whenever I try and use a file I get the error “Empty path name is not legal” 尝试使用“ CopyEx”时出现“无效名称”错误 - I get an “Invalid Name” error when I try to use “CopyEx” 错误“不支持指定的方法”。 获取调用栈 - Error 'specified method is not supported'. Get call stack 错误:不支持指定的方法? - Error: Specified method is not supported? 当我尝试从 mysql 数据库加载图像时,我收到错误“参数无效”,当我尝试从数据库加载图像时 - When I try to load image from mysql database i get error “Parameter is not valid” and when i try to load an image from db 使用ExcelDataReader.CreateReader()时,如何解决DateTime解析时出现System.FormatException错误? - How can I resolve a System.FormatException error on DateTime parsing when using ExcelDataReader.CreateReader()? 单元测试 controller 错误。 当我尝试在单元测试中使用 controller 时,出现此错误 - Unit testing controller error. When I try to use the controller in the unit test, I get this error 尝试连接数据库时出现“错误:无法初始化OLE”? C# - I get an “Error: Cannot initialize OLE” when I try to connect to a database? C# 尝试连接数据库时出现“错误:无法初始化OLE”? C# - I get an “Error: Cannot initialize OLE” when I try to connect to a database? C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM