简体   繁体   English

将Excel表转换为C#中的SQL表-将Excel中的多个列映射到SQL中的单个列

[英]Excel table to SQL table in C# - Mapping Multiple Columns in Excel to a Single Column in SQL

I am trying to upload individual ListObject tables in excel to SQL tables in a database. 我正在尝试将excel中的单个ListObject表上载到数据库中的SQL表。

I have already wrote code that simply generates an SQL query string and executes - this works but it's not easily maintainable. 我已经编写了仅生成SQL查询字符串并执行的代码-可以,但是不容易维护。

So I found this technique: https://stackoverflow.com/a/11268550/1610402 所以我发现了这种技术: https : //stackoverflow.com/a/11268550/1610402

This allows me to fill a data table and bulk insert that into SQL; 这使我可以填充数据表并将其批量插入SQL; with column mapping capabilities if they are required. 具有列映射功能(如果需要)。

However my table structure in Excel differs more than simply column 'names' to avoid redundant data. 但是,我在Excel中的表结构与为避免冗余数据而不仅仅是列“名称”的区别更多。

Therefore I need to map columns from Excel (example): 因此,我需要从Excel映射列(示例):

Column1    Column2   '2015'  '2016'  '2017'  '2018'  '2019'  '2020'
1          1          0.1     0.2     0.3     0.35    0.375   0.4
1          2          0.1     0.2     0.3     0.35    0.375   0.4

To columns in SQL, like the following: 到SQL中的列,如下所示:

Column1    Column2    Year    Value
1          1          2015    0.1
1          1          2016    0.2
1          1          2017    0.3
1          1          2018    0.35
1          1          2019    0.375
1          1          2020    0.4
1          2          2015    0.1
1          2          2016    0.2
1          2          2017    0.3
1          2          2018    0.35
1          2          2019    0.375
1          2          2020    0.4

Is there a better way of doing this in C# .Net or should I stick with my nested for loop and string builder? 在C#.Net中有更好的方法吗?还是应该坚持嵌套的for循环和字符串生成器?

The concept of what you want is called 'unpivoting'. 您想要的概念称为“不可透视”。 Whether you do this in C# or is not of importance, since you can simply load the first data in SQL-Server and unpivot this data by 是否使用C#进行操作无关紧要,因为您可以简单地将第一个数据加载到SQL-Server中,然后通过以下方式取消数据透视

SELECT IDENTITY(int,1,1) as RowId, Column1, Column2, [Year], [Value]
INTO newTable
FROM (
   SELECT Column1,Column2,[2015],[2016],[2017],[2018],[2019],[2020] FROM oldTable
) as source
UNPIVOT
(
   [Value] for [Year] in [2015],[2016],[2017],[2018],[2019],[2020]
) as target

The square brackets are required to make these strings appear as column names in stead of numbers or reserved words. 需要使用方括号使这些字符串显示为列名,而不是数字或保留字。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM