将Excel导入数据表

时间:2010-09-23 18:26:23

标签: c# winforms excel

我正在使用syncfusion将excel导入datattable。当数据导入datatable时,列都是字符串。如何将这些列转换为特定的数据类型?如何验证列数据类型?

using Syncfusion.XlsIO;

private void btnImport_Click(object sender, EventArgs e)
        {
            ImportExcelFile();
        }
 private void ImportExcelFile()
        {
            try
            {
                string strFileName = "";
                OpenFileDialog openFileDialog = new OpenFileDialog();

                openFileDialog.Filter = "Files (*.xls)|*.xls|(*.xlsm)|*.xlsm";
                openFileDialog.DefaultExt = ".xls";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    strFileName = openFileDialog.FileName;
                    #region Get Correct Worksheet in excel file
                    DateTime dtStart = DateTime.Now;
                    ExcelEngine excelEngine = new ExcelEngine();
                    IApplication application = excelEngine.Excel;
                    IWorkbook workbook = application.Workbooks.Open(strFileName);
                    IWorksheet sheet = workbook.Worksheets[0];
                    #endregion                


                    DataTable dt = sheet.ExportDataTable(sheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

                  dgIDCImport.GridDataSource(dt,ucGrid.GridTypes.IDCImport);

                    //Close the workbook.
                    workbook.Close();

                    //No exception will be thrown if there are unsaved workbooks.
                    excelEngine.ThrowNotSavedOnDestroy = false;
                    excelEngine.Dispose();



                }
            }

            catch (Exception err)
            {
                base.DisplayError(err);
            }
        }

1 个答案:

答案 0 :(得分:0)

而不是ColumnNames使用如下所示的DetectColumnType。

ExcelExportDataTableOptions.DetectColumnTypes

HTH