求 c# c/s结构中把datagrid中的数据导入到excel中程序 谢谢

解决方案 »

  1.   

    http://www.codeproject.com/csharp/excel_using_oledb.asp
    把别人的回复拿来看一下吧,
      

  2.   

    object def=Type.Missing;
    try
    {
    Excel.ApplicationClass excel=new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    Excel.Workbooks workbooks=excel.Workbooks;
    Excel._Workbook workbook=workbooks.Open(filename,def,def,def,def,def,def,def,def,def,def,def,def,def,def);//Excel.XlWBATemplate.xlWBATWorksheet
    Excel.Sheets sheets=workbook.Worksheets;
    Excel._Worksheet worksheet=(Excel._Worksheet)sheets.get_Item(i);
    int rowIndex=1; 
    int colIndex=1; 
    int row_cnt = ds.Tables[0].Rows.Count; 
    int col_cnt = ds.Tables[0].Columns.Count; 
    // ?用于用DataGridTableStyle自定?DataGrid?。 
    // for(int j = 0;j < col_cnt; j++) 
    // { 
    // excel.Cells[rowIndex,j + 1]= dg.TableStyles[0].GridColumnStyles[j].HeaderText; 
    // } 
    rowIndex++; 
    //同?方法?理数据 
    for(int row = 0; row < row_cnt; row++) 

    colIndex=1; 
    for(int col = 0; col < col_cnt; col++)          
    {                
    excel.Cells[rowIndex,colIndex] = dg[row, col]; 
    colIndex++; 

    rowIndex++; 

    //?置?元格数字内容?示格式 
    // Excel.Range range; 
    // range = worksheet.get_Range(worksheet.Cells[2,1], worksheet.Cells[row_cnt + 1, 1]); 
    // range.NumberFormat = "0000"; //?里是因?需要把0012等在Excel上正??示,默?会?成12 
    // range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; 
    // range= worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[row_cnt + 1,col_cnt]); 
    // // 内框及外框 
    // range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null); 
    // range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic; 
    // range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous; 
    // range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin; 
    // range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic; 
    // range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous; 
    // range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin; 
    excel.Columns.AutoFit(); 
    excel.Visible=true;