c#.net循环将DataGridView中的数据赋值到Excel中,并设置样式

 Microsoft.Office.Interop.Excel.Application excel =
                new Microsoft.Office.Interop.Excel.Application();
            excel.SheetsInNewWorkbook = 1;
            excel.Workbooks.Add();

            //设置Excel列名
            excel.Cells[1, 1] = "学号";
            excel.Cells[1, 2] = "姓名";
            excel.Cells[1, 3] = "性别";
            excel.Cells[1, 4] = "年级";
            excel.Cells[1, 5] = "电话";
            excel.Cells[1, 6] = "地址";
            excel.Cells[1, 7] = "出生年月日";
            excel.Cells[1, 8] = "邮箱";
            excel.Cells[1, 9] = "身份证号";

            //获取标题行的单元格,即Range第一行到第9列的区域创建一个range对象
            Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 9]);
            //设字体加粗
            range.Font.Bold = true;
            //设置字体颜色
            range.Font.ColorIndex = 0;
            //设置背景颜色
            range.Interior.ColorIndex = 15;
            //设置边框样式
            range.Borders.LineStyle = XlLineStyle.xlContinuous;

            //循环将DataGridView中的数据赋值到Excel中
            int i = 0, j = 0;
            //外循环,循环dgvStudents.Rows.Count整体行数
            for (i = 0; i < dgvStudents.Rows.Count; i++)
            {
                //通过for循环读前2列的数据
                for (j = 0; j < 2; j++)
                {
                    excel.Cells[i + 2, j + 1] = dgvStudents.Rows[i].Cells[j].Value.ToString();
                }
                //读取第3列的数据,设置性别
                excel.Cells[i + 2, 3] =
                    dgvStudents.Rows[i].Cells["Gender"].Value.ToString();

                //设置第4列到第9列的数据,设置电话的格式,通过NumberFormatLocal设置文本格式
                excel.get_Range(excel.Cells[i + 2, 5], excel.Cells[i + 2, 5]).NumberFormatLocal = "@";

                //设置第4列到第9列的数据,设置身份证号的格式,通过NumberFormatLocal设置文本格式
                excel.get_Range(excel.Cells[i + 2, 9], excel.Cells[i + 2, 9]).NumberFormatLocal = "@";
                //现在就可以读取第4列到第9列的数据
                for (j = 3; j < 9; j++)
                {
                    excel.Cells[i + 2, j + 1] = dgvStudents.Rows[i].Cells[j + 1].Value.ToString();
                }
            }
            //设置出生年月日的格式
            excel.get_Range(excel.Cells[2, 7], excel.Cells[i + 2, 7]).NumberFormat = "yyyy-m-d";

            //设置Excel水平对齐方式,左对齐
            excel.get_Range(excel.Cells[1, 1], excel.Cells[i + 2, 9]).HorizontalAlignment
                = XlHAlign.xlHAlignLeft;

            //设置列的宽度
            excel.get_Range("I1", "I9").ColumnWidth = 20;

            //显示当前窗口
            excel.Visible = true;