從數據庫導出數據到word、excel、.txt

using System;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using Excel;
using Word;
using System.IO;
namespace Common
{
/// <summary>
/// 把數據導入到.doc、.txt、.xls文件中
/// </summary>
public class Export
{
   private const string DATAWORDPATH = @"C:/folder/doc/datadoc/";
   private const string IMAGEWORDPATH = @"C:/folder/doc/imagedoc/";
   private const string IMAGEPATH = @"C:/folder/image/";
   private const string EXCELPATH = @"C:/folder/excel/";
   private const string TXTPATH = @"C:/folder/txt/";
   private const string IMAGEPOSTFIX = ".bmp";
   private const string WORDPOSTFIX = ".doc";
   private const string EXCELPOSTFIX = ".xls";
   private const string TXTPOSTFIX = ".txt";
   private const int DATADISTANCE = 5;
   private const int TABDISTANCE = 8;
  
   public Export()
   {
    //
    // TODO: 在此處添加構造函數邏輯
    //
   }

   /// <summary>
   /// 獲得數據集Dataset--------------------------------用於調試
   /// </summary>
   /// <returns>Dataset</returns>
   public DataSet GetData()
   {
    try
    {
     string sConnectionString;
     sConnectionString = "workstation id=GUOFU;packet size=4096;user id=sa;data source=GUOFU;persist security info=True;initial catalog=YC;password=sc";
     SqlConnection objConn = new SqlConnection(sConnectionString);
     objConn.Open();                                            
     SqlDataAdapter daPoint = new SqlDataAdapter("Select * From Point", objConn);
     DataSet dsYC = new DataSet("YC");
     daPoint.FillSchema(dsYC,SchemaType.Mapped, "Point");
     daPoint.Fill(dsYC,"Point");
     daPoint = new SqlDataAdapter("Select * From Employee", objConn);
     daPoint.FillSchema(dsYC,SchemaType.Mapped, "Employee");
     daPoint.Fill(dsYC,"Employee");
     return dsYC;
    }
    catch(Exception ex)
    {
     throw new Exception(ex.Message);
    }

   }

   /// <summary>
   /// 把數據文件導入到.xls文件
   /// </summary>
   /// <param name="ds"></param>
   public void ExportToExcel(DataSet ds)
   {

    if(ds.Tables.Count!=0)
    {
     //生成.xls文件完整路徑名
     string tempFileName = GetTempFileName();
     object filename = EXCELPATH+tempFileName+EXCELPOSTFIX;
     object Nothing = System.Reflection.Missing.Value;
    
     //創建excel文件,文件名用系統時間生成精確到毫秒
     Excel.Application myExcel = new Excel.ApplicationClass();
     myExcel.Application.Workbooks.Add(Nothing);

     try
     {
      //把Dataset中的數據插入excel文件中
      int totalCount = 0;
      for(int k =0;k<ds.Tables.Count;k++)
      {
       int row = ds.Tables[k].Rows.Count;
       int column = ds.Tables[k].Columns.Count;
    
       for(int i = 0;i<column;i++)
       {
        myExcel.Cells[totalCount+2,1+i] = ds.Tables[k].Columns[i].ColumnName;
       }

       for(int i = 0;i<row;i++)
       {
        for(int j =0;j<column;j++)
        {
         myExcel.Cells[totalCount+3+i,1+j] = "'" + ds.Tables[k].Rows[i][j].ToString();
        }
       }
       totalCount = totalCount + row +4;
      }

      try
      {
       //保存excel文件到指定的目錄下,文件名用系統時間生成精確到毫秒
       myExcel.ActiveWorkbook._SaveAs(filename,Nothing,Nothing,Nothing,Nothing,Nothing,XlSaveAsAccessMode.xlExclusive,Nothing,Nothing,Nothing,Nothing);
      }
      catch
      {
       System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+EXCELPATH+tempFileName+EXCELPOSTFIX);
       return;
      }
      //讓生成的excel文件可見
      myExcel.Visible = true;
     }
     catch(Exception e)
     {
      System.Windows.Forms.MessageBox.Show("向excel文件中寫入數據出錯:   " + e.Message);
     }
    }
    else
    {
     System.Windows.Forms.MessageBox.Show("No Data");
    }
   }


   /// <summary>
   /// 把數據導入到.doc文件
   /// </summary>
   /// <param name="ds"></param>
   public void ExportToWord(DataSet ds)
   {
    if(ds.Tables.Count!=0)
    {   
     string tempFileName = null;
     object filename = null;
    
     object tableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
     object autoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitFixed;

     object unit = Word.WdUnits.wdStory;
     object extend = System.Reflection.Missing.Value;
     object breakType = (int)Word.WdBreakType.wdSectionBreakNextPage;

     object count = 1;
     object character = Word.WdUnits.wdCharacter;

     object Nothing =   System.Reflection.Missing.Value;
    
     try
     {
      tempFileName = GetTempFileName();

      //生成.doc文件完整路徑名
      filename = DATAWORDPATH+tempFileName+WORDPOSTFIX;
     
      //創建一個word文件,文件名用系統時間生成精確到毫秒
      Word.Application myWord= new Word.ApplicationClass();
      Word._Document myDoc = new Word.DocumentClass();
      myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
      myDoc.Activate();

      //向把dataset中的表插入到word的文件中
    
      for(int totalTable = 0;totalTable<ds.Tables.Count;totalTable++)
      {
       myWord.Application.Selection.TypeText(ds.Tables[totalTable].TableName+"表的數據如下");
       myWord.Application.Selection.TypeParagraph();     
       myWord.Application.Selection.TypeParagraph();
       Word.Range para = myWord.Application.Selection.Range;
       myDoc.Tables.Add(para,ds.Tables[totalTable].Rows.Count+1,ds.Tables[totalTable].Columns.Count,ref tableBehavior,ref autoFitBehavior);
       for(int column = 0; column<ds.Tables[totalTable].Columns.Count;column++)
       {
        myDoc.Tables.Item(totalTable+1).Cell(1,column+1).Range.InsertBefore(ds.Tables[0].Columns[column].ColumnName.Trim());
       }    
       for(int row = 0;row<ds.Tables[totalTable].Rows.Count;row++)
       {
        for(int column = 0;column<ds.Tables[totalTable].Columns.Count;column++)
        {
         myDoc.Tables.Item(totalTable+1).Cell(row+2,column+1).Range.InsertBefore(ds.Tables[totalTable].Rows[row][column].ToString().Trim());
        }
       }
       myWord.Application.Selection.EndKey(ref unit,ref extend);
       myWord.Application.Selection.TypeParagraph();
       myWord.Application.Selection.TypeParagraph();
       myWord.Application.Selection.InsertBreak(ref breakType);    
      }
      myWord.Application.Selection.TypeBackspace();
      myWord.Application.Selection.Delete(ref character,ref count);
      myWord.Application.Selection.HomeKey(ref unit,ref extend);
    
      //保存word文件到指定的目錄下
      try
      {
       myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
       myWord.Visible = true;
      }
      catch
      {
       System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+DATAWORDPATH+tempFileName+WORDPOSTFIX);
       return;
      }
      //讓生成的excel文件可見
      myWord.Visible = true;
     }
     catch(Exception ex)
     {
      System.Windows.Forms.MessageBox.Show("向word文件中寫入數據出錯:   " + ex.Message);
     }
    }
    else
    {
     System.Windows.Forms.MessageBox.Show("No Data");
    }
   }
   /// <summary>
   /// 把圖片文件導入到.doc文件
   /// </summary>
   /// <param name="bp"></param>
   public void ExportToWord(Bitmap bp)
   {
    string tempFileName = null;
    string bmpPath = null;
    object filename = null;
    object Nothing = null;
    tempFileName = GetTempFileName();


    //生成.bmp文件完整路徑名
    bmpPath = IMAGEPATH+tempFileName+IMAGEPOSTFIX;

    //生成.doc文件完整路徑名
    filename = IMAGEWORDPATH+tempFileName+WORDPOSTFIX;
    Nothing = System.Reflection.Missing.Value;

    //創建一個word文件,文件名用系統時間生成精確到毫秒
    Word.Application myWord= new Word.ApplicationClass();
    Word._Document myDoc = new Word.DocumentClass();
    myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);  

    try
    {
     //把bitmap對象保存到系統所生成文件完整路徑中
     bp.Save(bmpPath);
    }
    catch
    {
     System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+bmpPath);
     return;
    }
  
    try
    {
     //往word文件中插入圖片
     myDoc.InlineShapes.AddPicture(bmpPath,ref Nothing,ref Nothing,ref Nothing);
    }
    catch
    {
     System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+bmpPath);
     return;
    }
  
    try
    {
     //保存word文件到指定的目錄下
     myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
    }
    catch
    {
     System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+IMAGEWORDPATH+tempFileName+WORDPOSTFIX);
     return;
    }

    //讓生成的word文件可見
    myWord.Visible = true;
   }


   /// <summary>
   /// 把數據文件導入到.txt文件
   /// </summary>
   /// <param name="ds"></param>
   public void ExportToTxt(DataSet ds)
   {

    if(ds.Tables.Count!=0)
    {
     string tempFileName = null;
     tempFileName = GetTempFileName();

  
     //創建一個.txt文件,文件名用系統時間生成精確到毫秒
     FileInfo file = new FileInfo(TXTPATH+tempFileName+TXTPOSTFIX);
     StreamWriter textFile = null;
     try
     {
      textFile = file.CreateText();
     }
     catch
     {
      System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件:   "+TXTPATH+tempFileName+TXTPOSTFIX);
      return;
     }

     //把Dataset中的數據寫入.txt文件中
     for(int totaltable = 0;totaltable<ds.Tables.Count;totaltable++)
     {
      //統計dataset中當前表的行數
      int row = ds.Tables[totaltable].Rows.Count;

      //統計dataset中當前表的列數
      int column = ds.Tables[totaltable].Columns.Count;

      //用於統計當前表中每列記錄中字符數最長的字符串的長度之和
      int totalLength = 0;

      //用於統計標題的長度(dataset中的表名的length+"表的數據如下"的length)
      int titleLength = 0;

      //統計每列記錄中字符數最長的字符串的長度
      int[] columnLength = new int[column];
      for(int i = 0;i<column;i++)
      {
       columnLength[i] = ds.Tables[totaltable].Columns[i].ColumnName.ToString().Length;
      }
      for(int i = 0;i<row;i++)
      {
       for(int j = 0;j<column;j++)
       {
        if(ds.Tables[totaltable].Rows[i][j].ToString().Length>columnLength[j])
        {
         columnLength[j]=ds.Tables[totaltable].Rows[i][j].ToString().Length;
        }
       }
      }


      //統計當前表中每列記錄中字符數最長的字符串的長度之和
      for(int i = 0;i<column;i++)
      {
       totalLength = totalLength+columnLength[i]+DATADISTANCE;
      }
      totalLength = totalLength+2*TABDISTANCE-DATADISTANCE;

      //統計標題的長度(dataset中的當前表名的length+"表的數據如下"的length)
      titleLength = ds.Tables[totaltable].TableName.ToString().Length+"表的數據如下".Length*2;

      //把標題寫入.txt文件中
      for(int i = 0;i<(int)((totalLength-titleLength)/2);i++)
      {
       textFile.Write(' ');
      }
      textFile.Write(ds.Tables[totaltable].TableName+"表的數據如下");
      textFile.WriteLine();
      for(int i = 0;i<totalLength;i++)
      {
       textFile.Write('*');
      }
      textFile.WriteLine();
      textFile.Write("/t");

      //把dataset中當前表的字段名寫入.txt文件中
      for(int i = 0;i<column;i++)
      {
       textFile.Write(ds.Tables[totaltable].Columns[i].ColumnName.ToString());
       for(int k = 0;k<columnLength[i]-ds.Tables[totaltable].Columns[i].ColumnName.ToString().Length+DATADISTANCE;k++)
       {
        textFile.Write(' ');
       }
      }
      textFile.WriteLine();
      for(int i = 0;i<totalLength;i++)
      {
       textFile.Write('-');
      }
      textFile.WriteLine();
      textFile.Write("/t");

      //把dataset中當前表的數據寫入.txt文件中
      for(int i = 0;i<row;i++)
      {
       for(int j = 0;j<column;j++)
       {
        textFile.Write(ds.Tables[totaltable].Rows[i][j].ToString());
        for(int k = 0;k<columnLength[j]-ds.Tables[totaltable].Rows[i][j].ToString().Length+DATADISTANCE;k++)
        {
         textFile.Write(' ');
        }
       }
       textFile.WriteLine();
       textFile.Write("/t");
      }
      textFile.WriteLine();
      for(int i = 0;i<totalLength;i++)
      {
       textFile.Write('-');
      }
      textFile.WriteLine();
      textFile.WriteLine();
      textFile.WriteLine();
     }

     //關閉當前的StreamWriter流
     textFile.Close();
     System.Windows.Forms.MessageBox.Show("數據文件已保存到"+"    "+file.FullName);                 
    }
    else
    {
     System.Windows.Forms.MessageBox.Show("No Data");
    }
   }

   public string GetTempFileName()
   {
    return DateTime.Now.ToString("yyyyMMddhhmmssfff");
   }
}
}

補充:使用以上方法必須對dcom進行配置,給用戶使用office的權限。
具體配置方法如下:
1:在服務器上安裝office的Excel軟件.
2:在"開始"->"運行"中輸入dcomcnfg.exe啓動"組件服務"
3:依次雙擊"組件服務"->"計算機"->"我的電腦"->"DCOM配置"
4:在"DCOM配置"中找到"Microsoft Excel 應用程序",在它上面點擊右鍵,然後點擊"屬性",彈出"Microsoft Excel 應用程序屬性"對話框
5:點擊"標識"標籤,選擇"交互式用戶"
6:點擊"安全"標籤,在"啓動和激活權限"上點擊"自定義",然後點擊對應的"編輯"按鈕,在彈出的"安全性"對話框中填加一個"NETWORK SERVICE"用戶(注意要選擇本計算機名),並給它賦予"本地啓動"和"本地激活"權限.
7:依然是"安全"標籤,在"訪問權限"上點擊"自定義",然後點擊"編輯",在彈出的"安全性"對話框中也填加一個"NETWORK SERVICE"用戶,然後賦予"本地訪問"權限.
這樣,我們便配置好了相應的Excel的DCOM權限.
注意:我是在WIN2003上配置的,在2000上,是配置ASPNET用戶

若不進行配置會出現錯誤
檢索 COM 類工廠中 CLSID 爲 {00024500-0000-0000-C000-000000000046} 的組件時失敗,原因是出現以下錯誤: 80070005。
原因是用戶沒有使用Excel的權限。
導出到word同樣要配置使用word的權限。  
繼續補充: 導出到txt我用了上面的方法有問題,
try
{
textFile = file.CreateText();
}
catch
{
System.Windows.Forms.MessageBox.Show("系統找不到指定目錄下的文件: "+TXTPATH+tempFileName+TXTPOSTFIX);
return;
}
總是在這裏跳到catch裏面。導出到word,excel都能用,繼續研究txt的使用方法 

發佈了14 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章