日期:2014-05-19  浏览次数:20853 次

如何把DataGridView中数据导出到 文本文档 和 EXCEL 以及 如何把 文本文档和 EXCE中数据倒入到 DataGridView
如何把DataGridView中数据导出到   文本文档   和   EXCEL   以及   如何把   文本文档和   EXCE中数据倒入到   DataGridView  

希望大家帮忙
多谢了

------解决方案--------------------
/// <summary>
/// 以操作Excel控件的方式将DataGridView数据导出到Excel add by sunny 2007/1/18
/// </summary>
/// <param name= "GridView "> DataGridView对象 </param>
/// <param name= "strExcelFile "> Excel文件名 </param>
/// <param name= "strError "> out参数,返回出错信息 </param>
/// <returns>
/// -1 出错
/// 0 成功
/// </returns>
public static int DataGridViewToExcel(System.Windows.Forms.DataGridView GridView,
string strExcelFileName,
out string strError)
{
strError = " ";
int nRet = 0;

Excel.Application xlApp = new Excel.Application();
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1

try
{
//~~
// 写字段名
for (int i = 0; i < GridView.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = GridView.Columns[i].HeaderText.ToString();
}

// 写记录
for (int i = 0; i < GridView.Rows.Count; i++)
{
for (int j = 0; j < GridView.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = GridView.Rows[i].Cells[j].Value.ToString(); ;
}
}

worksheet.Columns.EntireColumn.AutoFit();//自动适应每列的宽度 add by sunny.li
Excel.Range rg = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, GridView.Columns.Count]);
rg.Font.Bold = true;
workbook.Saved = true;
workbook.SaveCopyAs(strExcelFileName);

// 关掉内存中的进程
xlApp.Quit();
nRet = 0;
}
catch (Exception ex)
{
strError = ex.ToString();
nRet = -1;
}

return nRet;
}