求C#高手,Excel中单元格显示的是日期格式,当我读取到DataGridView中时,就变成了文本格式了
Excel中单元格显示的是日期格式,当我读取到DataGridView中时,就变成了文本格式了,这个要怎么解决呢?我用到的代码:DataSetds=GetWorkbook...
Excel中单元格显示的是日期格式,当我读取到DataGridView中时,就变成了文本格式了,这个要怎么解决呢?
我用到的代码:
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;
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);
}
我们要求这样操作Excel,不能用SQL的方式,这个主要是能把每个Sheet都要读出来,就像图2的那个下拉框里面的Sheet就是读取出来的
return dt;
}
现在我用newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).text解决了问题,但新的问题又来了,比如显示时间内容太长的单元格的值显示到DataGridView中会全部是“#####” 展开
我用到的代码:
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;
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);
}
我们要求这样操作Excel,不能用SQL的方式,这个主要是能把每个Sheet都要读出来,就像图2的那个下拉框里面的Sheet就是读取出来的
return dt;
}
现在我用newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).text解决了问题,但新的问题又来了,比如显示时间内容太长的单元格的值显示到DataGridView中会全部是“#####” 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询