【问题标题】:How to set custom format for cells like datetime in infragistics excel when exporting data to excel将数据导出到excel时如何为infragistics excel中的日期时间等单元格设置自定义格式
【发布时间】:2015-08-21 08:24:50
【问题描述】:

我正在使用 infragistics excel 导出到 excel。 我想将 excel 的列类型设置为与 db 的列类型相同。意味着如果列类型是 datetime,它应该在 infragistics excel 表中创建 datetime 列。

我试过下面的代码。

 Infragistics.Documents.Excel.Workbook workbook = new Infragistics.Documents.Excel.Workbook();

        // Create the worksheet to represent this data table
        Infragistics.Documents.Excel.Worksheet worksheet = workbook.Worksheets.Add(dtReportData.TableName);

        // Create column headers for each column
        for (int columnIndex = 0; columnIndex < dtReportData.Columns.Count; columnIndex++)
        {
            worksheet.Rows[0].Cells[columnIndex].Value = dtReportData.Columns[columnIndex].ColumnName;
        }

        // Starting at row index 1, copy all data rows in
        // the data table to the worksheet
        int rowIndex = 1;
        foreach (DataRow dataRow in dtReportData.Rows)
        {
            Infragistics.Documents.Excel.WorksheetRow row = worksheet.Rows[rowIndex++];

            for (int columnIndex = 0; columnIndex < dataRow.ItemArray.Length; columnIndex++)
            {
                row.Cells[columnIndex].Value = dataRow.ItemArray[columnIndex];

                if (dtReportData.Columns[columnIndex].DataType == Type.GetType("System.Decimal"))
                {

                    //Here column should be of type decimal.   

                }
                else if (dtReportData.Columns[columnIndex].DataType == Type.GetType("System.DateTime"))
                {
                   //Here column type should be of type datetime.                        
                }

            }

有人可以帮我解决这个问题吗..

【问题讨论】:

    标签: c# asp.net .net export-to-excel infragistics


    【解决方案1】:

    我不认为你可以直接设置列类型,我记得是由单元格值决定的,这里是一个示例,对于 double 我们以字符串格式传递,希望对您有所帮助。

        if (col.Definition.Type == DataType.Double)
        {
                .....
                    worksheet.Rows[r].Cells[column].CellFormat.FormatString = format;
        }
        else if (col.Definition.Type == DataType.DateTime)
        {
            ...
                worksheet.Rows[r].Cells[column].Value = col[row];
        }
        else if (col.Definition.Type == DataType.Boolean)
        {
            ...
            worksheet.Rows[r].Cells[column].Value = (bool) col[row];
        }
        else
        {
            // use string value, because some cell in the table is not a valid type in excel
            worksheet.Rows[r].Cells[column].Value = col[row].ToString();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2010-09-27
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多