读书人

怎么导出Excel

发布时间: 2013-11-01 14:43:02 作者: rapoo

如何导出Excel
我想把datagridview 中的数据导入excel 表格,请问具体代码是什么。
急求,在线等。
[解决办法]
首先要在项目中添加引用Microsoft.Office.Interop.Excel

//创建excel
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//设置工作表个数
excel.SheetsInNewWorkbook = 2;
//创建workbook
excel.Workbooks.Add();
Worksheet sheet1 = (Worksheet)excel.ActiveWorkbook.Worksheets[1];
//第一个工作表的名字
sheet1.Name = "导出学生数据";
//设置标题行列头
sheet1.Cells[1, 1] = "编号";
sheet1.Cells[1, 2] = "员工";
sheet1.Cells[1, 3] = "月份";
sheet1.Cells[1, 4] = "工资";
sheet1.Cells[1, 5] = "奖金";
sheet1.Cells[1, 6] = "医疗保险";
sheet1.Cells[1, 7] = "住房公积金";
sheet1.Cells[1, 8] = "养老";
sheet1.Cells[1, 9] = "扣除";
sheet1.Cells[1, 10] = "总计";

//设置标题行的样式
//获取标题行Range对象
Range range = sheet1.get_Range(sheet1.Cells[1, 1], sheet1.Cells[1, 10]);
//设置字体加粗
range.Font.Bold = true;
//设置字体颜色
range.Font.ColorIndex = 0;
//设置背景颜色
range.Interior.ColorIndex = 15;
//设置边框样式
range.Borders.LineStyle = XlLineStyle.xlDash;

int i = 0;
int j = 0;
//循环将DataGridView中的数据赋值到Excel中
//因为这里所使用的DataGridView控制中最后一行数据是空的
for (i = 0; i < dgvShowWageInfo3.Rows.Count; i++)
{

for (j = 0; j < 10; j++)
{
sheet1.Cells[i + 2, j + 1] = dgvShowWageInfo3.Rows[i].Cells[j].Value.ToString();


}

//设置出生年月日的格式
sheet1.get_Range(sheet1.Cells[2, 3], sheet1.Cells[i + 2, 3]).NumberFormat = "yyyy-m-d";
//显示当前窗口
excel.Visible = true;
}
[解决办法]
http://www.cnblogs.com/halo/archive/2012/02/29/2373859.html

读书人网 >.NET

热点推荐