標籤:
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;
c#.net迴圈將DataGridView中的資料賦值到Excel中,並設定樣式