将数据导到Excel后,如何将不必要的空列删掉?
注意:是导到Excel后,不要说通过Sql等处理后再导。或者我将DataGridView导出到Excel表,但其中有未知数量的列是不可见的,导出时我判断了不可见列不导出,但会形成空白列。
如这样:
 for (int i = 0; i < gvList.Columns.Count-1; i++)
            {
                if (gvList.Columns[i].Visible)
                {
                    VisibleCount++;
                    worksheet.Cells[2, i + 1] = gvList.Columns[i].Caption.ToString();
                    worksheet.get_Range(worksheet.Cells[2, i + 1], worksheet.Cells[2, i + 1]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐 
                    worksheet.get_Range(worksheet.Cells[2, i + 1], worksheet.Cells[2, i + 1]).Font.Bold = true;
                }
            }

解决方案 »

  1.   

    int j=0;
     for (int i = 0; i < gvList.Columns.Count-1; i++)
                {
                    if (gvList.Columns[i].Visible)
                    {
                        j++;
                        VisibleCount++;
                        worksheet.Cells[2, j + 1] = gvList.Columns[i].Caption.ToString();
                        worksheet.get_Range(worksheet.Cells[2, j+ 1], worksheet.Cells[2, j + 1]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐 
                        worksheet.get_Range(worksheet.Cells[2, j + 1], worksheet.Cells[2, j+ 1]).Font.Bold = true;
                    }
                }
      

  2.   

    to:forgot(忘记forgot2000) 汉 谢谢
      

  3.   

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    excel.Application.Workbooks.Add(true);    for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
              {
                  excel.Cells[1, i] = ds.Tables[0].Columns[i - 1].ColumnName.ToString();
              }
        for (int i = 2; i <= ds.Tables[0].Rows.Count + 1; i++)
              {
                    for (int j = 1; j <= ds.Tables[0].Columns.Count; j++)
                   {
                         excel.Cells[i, j] = ds.Tables[0].Rows[i - 2][j - 1].ToString();
                   }
              }
        excel.Visible = true;