日期:2014-05-18  浏览次数:21188 次

C# 获取Excel一个单元格的值,如果这个值为时间格式,获取出来的值怎么会是文本格式?求高手

如图,Excel中显示的是日期格式




但我读取到DataGridView中时,这个值却发生了变化



经过检查我发现这个问题是出在这里,如图


现在求大侠帮助了,怎么才能让日期值正确的显示到DataGridView中

C# code

DataSet ds = GetWorkbook(Application.StartupPath + @"\App_Data\Book1.xls");

public static DataSet GetWorkbook(string filename)
        {
            DataSet ds = new DataSet();
            Excel.Application app = new Excel.Application();    //初始化Excel对象
            app.Visible = false;
            app.DisplayAlerts = false;
            object missing = System.Reflection.Missing.Value;
            Excel.Workbook wb;// = app.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            try
            {
                wb = app.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
            foreach (Excel.Worksheet ws in wb.Sheets)
            {
                ds.Tables.Add(GetWorksheet(ws));
            }
            app.Workbooks.Close();
            app.Quit();
            return ds;
        }



public static DataTable GetWorksheet(Excel.Worksheet ws)
        {
            DataTable dt = new DataTable();
            dt.TableName = ws.Name;

            int row = ws.UsedRange.Rows.Count + 1;
            int col = ws.UsedRange.Columns.Count + 1;

            for (int c = 1; c < col; c++)
            {
                dt.Columns.Add("F" + c);
            }

            for (int r = 1; r < row; r++)
            {
                DataRow newRow = dt.NewRow();
                for (int c = 1; c < col; c++)
                {
                    newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).Value2;  //问题是不是出在这里,请问怎么解决呢
                }
                dt.Rows.Add(newRow);
            }

            return dt;
        }



请问下问题是不是出在:newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).Value2; //问题是不是出在这里,请问怎么解决呢


小弟在此谢过大侠们了!

------解决方案--------------------
你这个读取方法不是返回的是Dataset么?调试DataSet的数据,直接绑定DataGridView不就可以了?
------解决方案--------------------
你Excel直接把时间格式设置成文本试试吧
参考一下这个
http://www.cnblogs.com/ghypnus/archive/2012/03/23/2413474.html
希望对你有帮助
------解决方案--------------------
Convert.ToString(newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).text).ToString("yyyyMMdd");