/// <summary> ///Export Excel/// </summary> /// <param name= "MYDGV" >Control DataGridView</param> /// <param name= "dic" >title in English-Chinese comparison</param> Public Static voidExporttasks (DataGridView MYDGV, Dictionary <string,string>dic) {//define the Excel component interface to use//defines the Application object, which represents the entire Excel programMicrosoft.Office.Interop.Excel.Application Excelapp =NULL; //defines a Workbook object that represents the workbookMicrosoft.Office.Interop.Excel.Workbook Workbook; //defines a Worksheet object that represents a sheet in ExecelMicrosoft.Office.Interop.Excel.Worksheet ws =NULL; //defines a Range object that represents a range of cellsMicrosoft.Office.Interop.Excel.Range Range; intDcell =1; introwindex =0;intColindex =0; intRowCount =MYDGV. Rows.Count; intColCount =MYDGV. Columns.count; intDispcolcount =DiC. Count; Try { //initializes the Application object ExcelappExcelapp =NewMicrosoft.Office.Interop.Excel.Application (); //Create a task list on the first worksheet in a workbookWorkBook =ExcelApp.Workbooks.Add (Xlwbatemplate.xlwbatworksheet); WS= (Worksheet) workbook.worksheets[1]; //the name of the named sheet isWs. Name ="Sheet1"; //Create Cacheobject[,] Objdata =New Object[RowCount +1, ColCount]; //Create a title foreach(stringSinchDiC. Keys) {objdata[rowindex, Colindex++] =Dic[s]. ToString (); } //Get Data for(inti =0; i < rowcount; i++) {Dcell=0; foreach(stringSsinchDiC. Keys) { for(intj =0; J < ColCount; J + +) { if(MYDGV. COLUMNS[J]. Name = =SS) {Objdata[i+1, dcell++] = MYDGV. Rows[i]. CELLS[J]. Formattedvalue.tostring ();//get the value after the style } } } } //writing to ExcelRange = Ws.get_range (excelapp.cells[1,1], Excelapp.cells[rowcount, Dispcolcount]); Range. Value2=Objdata; System.Windows.Forms.Application.DoEvents (); //Set FormatExcelApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;//Global left AlignmentExcelApp.Cells.EntireColumn.AutoFit (); Range= Ws.get_range (excelapp.cells[1,1], excelapp.cells[1, ColCount]); Range. Font.Bold=true;//title Bold//Show ExcelExcelapp.visible =true; } Catch(Exception ex) {Throwex; }
DataGridView Data Export to Excel