Microsoft.Office.Interop.Excel.Application Excel =
New Microsoft.Office.Interop.Excel.Application ();
Excel. SheetsInNewWorkbook = 1;
Excel. Workbooks.Add ();
//Set Excel column names
Excel. Cells[1, 1] = "study number";
Excel. Cells[1, 2] = "name";
Excel. Cells[1, 3] = "gender";
Excel. Cells[1, 4] = "Grade";
Excel. Cells[1, 5] = "Telephone";
Excel. Cells[1, 6] = "Address";
Excel. Cells[1, 7] = "Date of birth";
Excel. Cells[1, 8] = "Mailbox";
Excel. Cells[1, 9] = "Social Security number";
//Gets the cell of the header row, which is the range from the first row to the 9th column to create a Range object
Range range = Excel.get_range (Excel. Cells[1, 1], Excel. Cells[1, 9]);
//Set font bold
range. Font.Bold = true;
//Set font color
range. Font.ColorIndex = 0;
//Set background color
range. Interior.ColorIndex = 15;
//Set border style
range. Borders.LineStyle = xllinestyle.xlcontinuous;
Loop to assign data in DataGridView to Excel
int i = 0, j = 0;
Outer loop, loop dgvStudents.Rows.Count total number of rows
for (i = 0; i < DgvStudents.Rows.Count; i++)
{
Read the first 2 columns of data through a for loop
for (j = 0; J < 2; J + +)
{
Excel. Cells[i + 2, j + 1] = Dgvstudents.rows[i]. CELLS[J]. Value.tostring ();
}
Read the 3rd column of data, set the gender
Excel. Cells[i + 2, 3] =
Dgvstudents.rows[i]. cells["Gender"]. Value.tostring ();
Set the data in columns 4th through 9th, format the phone, format the text by numberformatlocal
Excel.get_range (Excel. Cells[i + 2, 5], Excel. Cells[i + 2, 5]). NumberFormatLocal = "@";
Set the data in columns 4th through 9th, format the ID number, and format the text with numberformatlocal
Excel.get_range (Excel. Cells[i + 2, 9], Excel. Cells[i + 2, 9]). NumberFormatLocal = "@";
Data from columns 4th through 9th can now be read
for (j = 3; J < 9; J + +)
{
Excel. Cells[i + 2, j + 1] = Dgvstudents.rows[i]. Cells[j + 1]. Value.tostring ();
}
}
Format date of Birth month
Excel.get_range (Excel. Cells[2, 7], Excel. Cells[i + 2, 7]). NumberFormat = "yyyy-m-d";
Set Excel horizontal alignment, left-aligned
Excel.get_range (Excel. Cells[1, 1], Excel. Cells[i + 2, 9]). HorizontalAlignment
= Xlhalign.xlhalignleft;
Set the width of a column
Excel.get_range ("I1", "I9"). ColumnWidth = 20;
Show Current Window
Excel. Visible = true;
The c#.net loop assigns the data in the DataGridView to Excel and sets the style