asp.Net excelデータをエクスポートする一般的な方法の概要

14930 ワード

本文の例はaspを述べた.Netでよく使われるexcelデータのエクスポート方法と、データのインポートやエクスポート時に遭遇する可能性のある問題のまとめを紹介し、参考にしてください.文章があなたに役に立つことを望んでいます.具体的な実現方法は以下の通りである.
1、datasetから生成

   public void CreateExcel(DataSet ds,string typeid,string FileName)  
  
  {
   HttpResponse resp;
   resp = Page.Response;
   resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);   
   string colHeaders= "", ls_item="";
   int i=0;
 
   // , DataSet
   DataTable dt=ds.Tables[0];
   DataRow[] myRow=dt.Select(""); 
   // typeid=="1" EXCEL ;typeid=="2" XML
   if(typeid=="1")
   {
    // , t ,
    for(i=0;i     colHeaders+=dt.Columns[i].Caption.ToString()+"t";
    colHeaders +=dt.Columns[i].Caption.ToString() +"n";   
    // HTTP
    resp.Write(colHeaders); 
    //   
    foreach(DataRow row in myRow)
    {
     // , , t , n
     for(i=0;i      ls_item +=row[i].ToString() + "t";     
     ls_item += row[i].ToString() +"n";
     // HTTP , ls_item     
     resp.Write(ls_item);
     ls_item="";
    }
   }
   else
   {
    if(typeid=="2")
    { 
     // DataSet XML HTTP
     resp.Write(ds.GetXml());
    }    
   }
   // HTTP
   resp.End();
}

2、datagridから生成

   public void ToExcel(System.Web.UI.Control ctl)   
  
  {
   HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
   HttpContext.Current.Response.Charset ="UTF-8";    
   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
   HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
   ctl.Page.EnableViewState =false;   
   System.IO.StringWriter  tw = new System.IO.StringWriter() ;
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
   ctl.RenderControl(hw);
   HttpContext.Current.Response.Write(tw.ToString());
   HttpContext.Current.Response.End();
  }

 
使用法:ToExcel(datagrid 1); 
 
3、これはdataview

   public void OutputExcel(DataView dv,string str) 
  
{
   //
   // TODO:
   //
   //dv Excel ,str
   GC.Collect();
   Application excel;// = new Application();
   int rowIndex=4;
   int colIndex=1;
 
   _Workbook xBk;
   _Worksheet xSt;
 
   excel= new ApplicationClass();
  
   xBk = excel.Workbooks.Add(true);
   
   xSt = (_Worksheet)xBk.ActiveSheet;
 
   //
   //
   //
   foreach(DataColumn col in dv.Table.Columns)
   {
    colIndex++;
    excel.Cells[4,colIndex] = col.ColumnName;
    xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
   }
 
   //
   //
   //
   foreach(DataRowView row in dv)
   {
    rowIndex ++;
    colIndex = 1;
    foreach(DataColumn col in dv.Table.Columns)
    {
     colIndex ++;
     if(col.DataType == System.Type.GetType("System.DateTime"))
     {
      excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
     }
     else
      if(col.DataType == System.Type.GetType("System.String"))
     {
      excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
     }
     else
     {
      excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
     }
    }
   }
   //
   //
   //
   int rowSum = rowIndex + 1;
   int colSum = 2;
   excel.Cells[rowSum,2] = " ";
   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
   //
   //
   //
   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;// , 56
   //
   //
   //
   excel.Cells[2,2] = str;
   //
   //
   //
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
   //
   //
   //
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
   //
   //
   //
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
   //
   //
   //
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//
   xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//
   xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//
   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//
   //
   //
   //
   excel.Visible=true;
 
   //xSt.Export(Server.MapPath(".")+"\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
   xBk.SaveCopyAs(Server.MapPath(".")+"\"+this.xlfile.Text+".xls");
 
   ds = null;
            xBk.Close(false, null,null);
   
            excel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
            xBk = null;
            excel = null;
   xSt = null;
            GC.Collect();
   string path = Server.MapPath(this.xlfile.Text+".xls");
 
   System.IO.FileInfo file = new System.IO.FileInfo(path);
   Response.Clear();
   Response.Charset="GB2312";
   Response.ContentEncoding=System.Text.Encoding.UTF8;
   // , " / "
   Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
   // , ,
   Response.AddHeader("Content-Length", file.Length.ToString());
   
   // ,
   Response.ContentType = "application/ms-excel";
   
   //
   Response.WriteFile(file.FullName);
   //
  
   Response.End();
}
 
 
EXCELをインポート、エクスポートする問題の概要
一、プロジェクトへの参照の追加:プロジェクトエクスプローラの参照-->参照の追加-->選択を右クリックします.NETタブ-->Microsoftを選択します.Office.Interop.Excel-->OK;選択するときに注意してください.NETコンポーネントのバージョン番号、この例の12.0.0.0はOffice 2007のバージョンです:二、プロジェクトでMicrosoftを使用します.Office.Interop.Excel:Microsoftを使用したい場合.Office.Interop.Excel、まずプロジェクトで名前空間を参照する必要があります:using Microsoft.Office.Interop.Excel; 三、Excelを創立する.アプリケーション関連オブジェクト

   //  Application   
  
        Microsoft.Office.Interop.Excel.Application myExcel = new Application();
  // Workbooks
         Workbooks myBooks = myExcel.Application.Workbooks;
     // System.Reflection.Missing object
        object oMissing = System.Reflection.Missing.Value;

四、Excelのbookファイルを開くか新規作成する

   //  Excel  ,    “ExccelFilePath” Excel            ,      
  
  Workbook myBook = myBooks.Open(ExccelFilePath,oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
     // Workseet ,, , : , :“sheet1”/“Sheet2”
     Worksheet mySheet = (Worksheet)myBook.Worksheets[1];
    // EXCEL ,   , ,
    Workbook workbook1 = excel1.Workbooks.Add(true);
    Worksheet mySheet= (Worksheet)workbook1.Worksheets["sheet1"];
    // EXCEL , false
    myExcel.Visble=true;

五、いくつかの重要なExcelに対する操作1、Rangeオブジェクト①を取得し、一つのセルのRangeオブジェクトを取得する:

   //     、           Range   
  
            Range r = (Excel.Range)mySheet.Cells[1, 1];
          // Range
   Range r=(Excel.Range)Range.get_Range("A1:F3")

②、セルに値を割り当てる、またはセルの値を取り出す:
        

   //    Range     : 
  
   r.Text=" ";
       // Range :
        mySheet.Cells[1,2].Text=" ";
     // Range :
   String strValue= r.Text;
       // Range :
    String  strValue=  mySheet.Cells[1,2].Text;

③、セルに外枠を設ける
        

   mySheet.Cells[2, 1].BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);//   
 

④、セルのマージ
  

   //                   Range   
  
            Range r=Range.get_Range("A1:F3");
  //
         r.MergeCells = true;

⑤、セルのフォント、サイズ、背景色などの属性を設定する
    

   mySheet.Cells[1, 1].Font.Name = "  "; 
  
        mySheet.Cells[1, 1].Font.Size = 20;
        mySheet.Rows["1:1"].RowHeight = 40;
    mySheet.Cells[1, 1].Interior.Color = Color.FromArgb(224, 224, 224);//

⑥、1行削除:
   

   //          Range 
  
    Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)mySheet.Rows[sendedRow[1], Type.Missing];
   // , ,
       range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);

⑦、データを取得した行数
   

   int rowsint = mySheet.UsedRange.Cells.Rows.Count; 
 

六、EXCELファイルの保存と退出
1、EXCELの保存と退出

   myBook.Save(); 
  
   myBooks.Close();
   myExcel.Quit();

2、EXCEL指定ファイル保存

   myBook.Close(true, FilePath +_file_Name, null); 
 

七、EXCLE対象の資源を解放し、EXCELプロセスを終了するこの方面の内容について多くのネットユーザーが多種の方法を話している.
1、以上のEXCELに対する操作を一つの方法に入れる.
2.EXCELを操作した後、直ちに使用しないオブジェクトを1つずつ解放し、null値を付与する.
  

   System.Runtime.InteropServices.Marshal.ReleaseComObject(mysheet); 
  
  mysheet=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
  myBook=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myBooks);
  myBooks=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
  myExcel=null;

3、もう一つの方法を新規作成し、その方法で上記新規の操作EXCEL方法を実行し、操作EXCEL方法を実行した後にGCを追加する.Collect():

   //     OutPutEXCEL()     EXCEL    EXCEL       
  
private void killExcel()
{
  outPutEXCEL();
  GC.Collect();
  GC.WaitForPendingFinalizers();
}

多くのネットユーザーがGCの使用を紹介している.Collect()EXCELが占有するリソースを解放してEXCELの進行を終了し、「GC.Collect();EXCELを操作する業務と1つのブロックに書かれていて、「GC」はEXCELプロセスを永遠に終了することはできません.WEBアプリケーションでは、このような現象は恐ろしいことです.なぜならGCは本ブロックのゴミメモリをクリーンアップしないからです.
4、ビジネスイベントでkillEXCEL()メソッドを呼び出す:

   protected void LinkButton3_Click(object sender, EventArgs e) 
  
{
  // EXCEL
  killExcel();
}

八、いくつかの権限の基本設定:
以上の方法を使用して、開発環境ではデバッガに問題はありません.サーバにパブリッシュされた後も、プログラムが正常に動作しない場合は、次の権限設定が必要です.
.NETはExcelで発生した800700005エラーの解決方法をエクスポートします.
COM系ファクトリにおけるCLSIDが{00024500-00000-00000-2000-C 00000-00000,046}のコンポーネントを検索中に失敗したのは、以下のエラーが発生するためである:80070005基本上.Net excelファイルをエクスポートするには、このように構成する必要があります.構成しない場合は間違いありませんが、構成後は基本的にエラーはありません.具体的な配置方法は以下の通りである:1サーバにofficeのExcelソフトウェアをインストールする.②「スタート」->「運転」にdcomcnfgを入力.exe「コンポーネントサービス」③「コンポーネントサービス」->「コンピュータ」->「マイコンピュータ」->「DCOM構成」④「DCOM構成」で「Microsoft Excelアプリケーション」を順番にダブルクリックし、その上で右クリックして「プロパティ」をクリックし、「Microsoft Excelアプリケーションプロパティ」ダイアログボックス⑤「識別」タブをクリックし、「インタラクティブユーザー」⑥「セキュリティ」タブを選択し、「起動とアクティブ権限」で「カスタム」をクリックします.その後、対応する「編集」ボタンをクリックし、ポップアップの「セキュリティ」ダイアログボックスに「NETWORK SERVICE」ユーザー(本コンピュータ名を選択することに注意)を記入し、「ローカル起動」と「ローカルアクティブ化」の権限を与える.⑦依然として「セキュリティ」タブである、「アクセス権限」で「カスタム」をクリックし、「編集」をクリックし、ポップアップされた「セキュリティ」ダイアログボックスにも「NETWORK SERVICE」ユーザーを記入し、「ローカルアクセス」権限を与える.⑧インタラクティブユーザ設定後にエラー8000401 aが発生した場合、インタラクティブユーザをキャンセルしadministratrとして指定することで、この問題を一時的に解決することができる.さらなる解決策はまだ検討されている.⑨8点目の設定をすると、Excelを開くと「オブジェクト参照やリンクは使用できません」となり、セルの貼り付けができなくなる場合があります.原因は不明ですが、設定をキャンセルすると消えます.
皆さんのaspについてお話ししたいと思います.Netプログラミングが役立ちます.