2

I have a function to export datagridview to excel using CloedXML. Everything works ok, BUT:

I add columns from datagridview to datatable using

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

This uses column.Name which is Design (Name) in my dgv. I want to add 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, ...). 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.

            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++;
             }
tomiteko
  • 49
  • 1
  • 8

1 Answers1

0

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. 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.

Also, I couldn't tell from your example, but I think you may be misunderstanding what the type parameter is for. It is for setting the variable type that the DataColumn holds. You do not need to specify typeof(string) because the default type of a DataColumn is string.

tehDorf
  • 775
  • 1
  • 11
  • 32
  • that typeof(string) was just a shot..I get it now.. I don't know if I explained the situation well. My code adds columm headers to excel. But exporting rows is broken. It only exports values "under" columns with no special char or spaces. this is my function to write rows to excel: foreach (int columnindex in columnsList) { worksheet.Cell(1, col_).Value = dt.Columns[columnindex].ToString(); col_++; } – tomiteko Jan 07 '15 at 22:46