润宇betvictor85
业务介绍:betvictor xin1946betvictor85公司、betvictor85开发、betvictor85定制、betvictor85外包
betvictor85
方案
文章

betvictor85|betvictor xin1946|伟德国际 伟德官网

发布时间:2015/8/13  浏览次数:7次  字体【    】

private void ExportExcel(string fileName, DataGridView myDGV)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}

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

//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
//写入数值
for (int r = 0; r < myDGV.Rows.Count; r++)
{
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}

}
xlApp.Quit();
GC.Collect();//强行销毁
MessageBox.Show(fileName + "保存成功", "提示", MessageBoxButtons.OK);
}

 
西部IT网合作伙伴
合作伙伴
© 版权所有:betvictor xin1946润宇betvictor85科技有限公司 
公司地址:betvictor xin1946市碑林区 联系电话:029-87878512 手机:13468700578 联系人:李先生
Copyright ® 2009-2015 RunYusoft.com Inc. All Rights Reserved 
技术支持:betvictor xin1946润宇betvictor85科技有限公司  陕ICP备11000720号-3