c# 将datagridview 生成为excel
来源:互联网 发布:田径跑道数据 编辑:程序博客网 时间:2024/06/06 07:47
private int ExportExcel(string strCaption, DataGridView myDGV)
{
int result = 9999;
// 列索引,行索引,总列数,总行数
int ColIndex = 0;
int RowIndex = 0;
int ColCount = myDGV.ColumnCount;
int RowCount = myDGV.RowCount;
if (myDGV.RowCount == 0)
{
result = 1;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
result = 2;
}
try
{
// 创建Excel工作薄
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
// 设置标题
Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = strCaption;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
// 创建缓存数据
object[,] objData = new object[RowCount + 1, ColCount];
//获取列标题
foreach (DataGridViewColumn col in myDGV.Columns)
{
objData[RowIndex, ColIndex++] = col.HeaderText;
}
// 获取数据
for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
{
for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
{
if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";
{
objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
}
else
{
objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
}
}
System.Windows.Forms.Application.DoEvents();
}
// 写入Excel
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
range.Value2 = objData;
//保存
xlBook.Saved = true;
xlBook.SaveCopyAs(@"D:/报表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
//返回值
result = 0;
}
- c# 将datagridview 生成为excel
- C#将DataGridView中的数据保存为EXCEL的方法
- C#将DataGridView中的数据导出为EXCEL
- C#将DataGridView中的数据导出为EXCEL
- C#将DataGridView中的数据导出为EXCEL
- C#将DataGridView中的数据导出为EXCEL
- C#将DataGridView中的数据导出为EXCEL
- C# DataGridView导出为Excel .
- 将DataGridView导出为Excel的函数
- 将datagridview数据导出为excel文件
- c# 实现将Excel导入到dataGridView
- c#将datagridview信息导入excel
- C# winform 将dataGridView导出到excel
- C# WinForm下DataGridView导出生成Excel
- C# 中利用DataGridView将数据库中的信息导出为Excel
- C# datagridview 转换为 word excel
- C#操作Excel,将DataGridView数据导出到Excel中
- C#操作Excel,将DataGridView数据导出到Excel中
- POST
- 让gedit成为强大的C语言IDE
- skyeye在ubuntu上的安装
- Linux下Tomcat的启动、关闭、杀死进程
- protected成员访问规则
- c# 将datagridview 生成为excel
- November 2009
- GoldenGate TDM容灾方案与DataGuard容灾方案的对比
- prototype.js中class类详解
- 项目中的名称约定规则
- ubuntu9.10 qq自动退出修复
- 构建交叉编译工具链
- 解决 ASP.NET Chart 控件出错 为 ChartImg.axd 执行子请求时出错。
- 页眉和页脚去线法