简体   繁体   English

将ClosedXML导出列标题转换为excel [C#]

[英]ClosedXML export column header to excel [C#]

I have a function to export datagridview to excel using CloedXML. 我具有使用CloedXML将datagridview导出到excel的功能。 Everything works ok, BUT: 一切正常,但是:

I add columns from datagridview to datatable using 我使用以下方式将列从datagridview添加到datatable

            foreach (DataGridViewColumn column in dgvLoadAll.Columns)
            {
                dt.Columns.Add(column.Name);
            }

This uses column.Name which is Design (Name) in my dgv. 这使用column.Name在我的dgv中是Design(名称)。 I want to add column.HeaderText. 我想添加column.HeaderText。 When I use 当我使用

            dt.Columns.Add(column.HeaderText, typeof(string));

it adds column headers sucessfully, but export does not work ok. 它成功添加了列标题,但是导出无法正常进行。 It only exports columns where there are no special characters or even blank char. 它仅导出没有特殊字符甚至没有空白字符的列。 ("Name" column is exported, but "IUPAC Name", or "Čas" is not, ...). (“名称”列已导出,但“ IUPAC名称”或“Čas”未导出,...)。 Renaming is not an option. 重命名不是一种选择。

Here is the part of export function responsible for writing cells. 这是导出功能的一部分,负责编写单元格。 Just reminder: It works 100% OK when I use column.Name. 提醒一下:当我使用column.Name时,它可以100%确定。

            foreach (int rowindex in rowsselected)
            { 
                foreach (int columnindex in columnsList)
                {                    
                        worksheet.Cell(k+2, j+1).Value = dt.Rows[rowindex] [columnindex].ToString();
                        j++;
                }
              j = 0;
              k++;
             }

From what it looks like on MSDN for DataColumnCollection.Add(string columnName, Type type) and in their examples , columnName is for setting the variable name of the new DataColumn. 从MSDN DataColumnCollection.Add(string columnName, Type type)及其示例中的columnName用于设置新DataColumn的变量名称 That means you are limited to valid variable names as input, which would explain why spaces and special characters do not work. 这意味着您只能使用有效的变量名作为输入,这将解释为什么空格和特殊字符不起作用。 I would imagine that _Name , Address1 , Zip_Code , etc. would work. 我可以想象_NameAddress1Zip_Code ,等会工作。

Also, I couldn't tell from your example, but I think you may be misunderstanding what the type parameter is for. 另外,我无法从您的示例中看出来,但我认为您可能会误解type参数的用途。 It is for setting the variable type that the DataColumn holds. 它用于设置DataColumn保存的变量类型 You do not need to specify typeof(string) because the default type of a DataColumn is string . 您不需要指定typeof(string)因为DataColumn的默认类型是string

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

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