導出數據到excel的三種方法

 方法一:
1.首先聲明,這些方法也都是本人蒐集的資料,然後爲已所用,程序中不足之處,還請高手指點.
2.網上有好多關於用SQL語句導入導出的例子,這裏不再重複寫了。
方法1:調用com組件,導出access數據到Excel,就是直接調用access的導出功能,此方法速度超級快
using Access;
Access.ApplicationClass oAccess = new Access.ApplicationClass();
oAccess.Visible = false;
try
{
//ACCESS9:
oAccess.OpenCurrentDatabase("d://wcf.mdb",false,"");
//導出到excel
oAccess.DoCmd.TransferSpreadsheet(Access.AcDataTransferType.acExport,Access.AcSpreadSheetType.acSpreadsheetTypeExcel9,"工作表名","d://wcf.xls",true,null,null);
//導入txt
//oAccess.DoCmd.TransferText(Access.AcTextTransferType.acExportDelim,"","Enterprise","d://wcf.txt",true,"",0);
oAccess.CloseCurrentDatabase();
oAccess.DoCmd.Quit(Access.AcQuitOption.acQuitSaveNone);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oAccess);
oAccess = null;
MessageBox.Show("導入成功");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
GC.Collect();
}
方法2:此方法速度也是超級快,只不過導出的格式非標準的Excel格式,默認工作表名與文件名相同
string FileName="d://abc.xls";
System.Data.DataTable dt=new System.Data.DataTable();
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine="";
objFileStream = new FileStream(FileName,FileMode.OpenOrCreate,FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream,System.Text.Encoding.Unicode);

for(int i=0;i<dt.Columns.Count;i++)
{
strLine=strLine+dt.Columns[i].ColumnName.ToString()+Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine="";


for(int i=0;i<dt.Rows.Count;i++)
{
strLine=strLine+(i+1)+Convert.ToChar(9);
for(int j=1;j<dt.Columns.Count;j++)
{
strLine=strLine+dt.Rows[i][j].ToString()+Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine="";
}
objStreamWriter.Close();
objFileStream.Close();


方法3:用Ado.net 此方法速度較以上兩個顯得慢了一些,數據量越大越明顯
int Id=0;
string Name="測試";
string FileName="d://abc.xls";
System.Data.DataTable dt=new System.Data.DataTable();
long totalCount=dt.Rows.Count;
long rowRead=0;
float percent=0;
OleDbParameter[] parm=new OleDbParameter[dt.Columns.Count];
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objConn.Open();
//建立表結構
objCmd.CommandText = @"CREATE TABLE Sheet1(序號 Integer,名稱 varchar)";
objCmd.ExecuteNonQuery();
//建立插入動作的Command
objCmd.CommandText = "INSERT INTO Sheet1("+Id+","+Name+")";
parm[0]=new OleDbParameter("@Id", OleDbType.Integer);
objCmd.Parameters.Add(parm[0]);
parm[1]=new OleDbParameter("@Company", OleDbType.VarChar);
objCmd.Parameters.Add(parm[1]);
//遍歷DataTable將數據插入新建的Excel文件中
for(int i=0;i<dt.Rows.Count;i++)
{  
parm[0].Value=i+1;
for(int j=1;j<parm.Length;j++)
{
parm[j].Value =dt.Rows[i][j];
}
objCmd.ExecuteNonQuery();
rowRead++;
percent=((float)(100*rowRead))/totalCount;  
//this.FM.CaptionText.Text = "正在導出數據,已導出[" + percent.ToString("0.00") + "%]...";
if(i==dt.Rows.Count-1)
//this.FM.CaptionText.Text = "請稍後......";
System.Windows.Forms .Application.DoEvents();
}
objConn.Close();
//this.FM.CaptionText.Text = "";


方法4:此方法調用com組件,速度都慢於以上3個方法
using Excel;


System.Data.DataTable dt=new System.Data.DataTable();
string FileName="d://abc.xls";


long totalCount=dt.Rows.Count;
long rowRead=0;
float percent=0;
Excel.Application xlApp=null;
xlApp=new Excel.Application();
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;


//寫入字段
for(int i=0;i<dt.Columns.Count;i++)
{
worksheet.Cells[1,i+1]=dt.Columns[i].ColumnName; 
range=(Excel.Range)worksheet.Cells[1,i+1];
}
for(int r=0;r<dt.Rows.Count;r++)
{
worksheet.Cells[r+2,1]=r+1;
for(int i=0;i<dt.Columns.Count;i++)
{
//worksheet.Cells[r+2,i+1]=dt.Rows[r][i];
if(i+1!=dt.Columns.Count)
worksheet.Cells[r+2,i+2]=dt.Rows[r][i+1];
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;  
//this.FM.CaptionText.Text = "正在導出數據,已導出[" + percent.ToString("0.00") + "%]...";
System.Windows.Forms .Application.DoEvents();
}
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[dt.Rows.Count+2,dt.Columns.Count]);
workbook.Saved =true;
workbook.SaveCopyAs(FileName);
//this.FM.CaptionText.Text = "";


方法5:利用剪貼板 ,有人說此方法很快,但是我用時,這種方法最慢,請高手指點.
System.Data.DataTable dt=new System.Data.DataTable();
string filePath=@"d:/abc.xls";


object oMissing = System.Reflection.Missing.Value;
Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
try
{
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
Excel.Workbooks oBooks = xlApp.Workbooks;
Excel._Workbook xlWorkbook = null;
xlWorkbook = oBooks.Open(filePath,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,
oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing);


Excel.Worksheet xlWorksheet;
// 添加入一個新的Sheet頁。
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
// 以TableName作爲新加的Sheet頁名。
xlWorksheet.Name ="企業名錄";
// 取出這個DataTable中的所有值,暫存於stringBuffer中。
string stringBuffer = "";


for( int j=0; j<dt.Rows.Count; j++ )
{
for( int k=0; k<dt.Columns.Count; k++ )
{
stringBuffer += dt.Rows[j][k].ToString();
if( k < dt.Columns.Count - 1 )
stringBuffer += "/t";
}
stringBuffer += "/n";
}
// 利用系統剪切板
System.Windows.Forms.Clipboard.SetDataObject("");
// 將stringBuffer放入剪切板。
System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
// 選中這個sheet頁中的第一個單元格
((Excel.Range)xlWorksheet.Cells[1,1]).Select();
// 粘貼!
xlWorksheet.Paste(oMissing,oMissing);
// 清空系統剪切板。
System.Windows.Forms.Clipboard.SetDataObject("");


// 保存並關閉這個工作簿。
xlWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
xlWorkbook = null;


這些方法都沒有關閉Excel進程,這種資料很多,在此不多寫了,希望這些能對一些人帶來方便.


方法二:
private void btnExport_Click(object sender, System.EventArgs e)
{
 if(this.savFileExcel.ShowDialog()==DialogResult.OK)
 {
  string zgh="";
  string xm="";
  string xbmc="";
  string yhid="";
  string FileName=savFileExcel.FileName;
  DataTable dt=new DataTable();
  long totalCount=dt.Rows.Count;
  long rowRead=0;
  float percent=0;
  OleDbParameter[] parm=new OleDbParameter[dt.Columns.Count];
  string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +";Extended Properties=Excel 8.0;";
  OleDbConnection objConn = new OleDbConnection(connString);
  OleDbCommand objCmd = new OleDbCommand();
  objCmd.Connection = objConn;
  objConn.Open();
  //建立表結構
  objCmd.CommandText = @"CREATE TABLE Sheet1(職工號 varchar,姓名 varchar,性別 varchar,用戶名 varchar)";
  objCmd.ExecuteNonQuery();
  //建立插入動作的Command
  try
  {
   objCmd.CommandText = "insert into Sheet1("+zgh+","+xm+","+xbmc+","+yhid+")";
   parm[0]=new OleDbParameter("@zgh", OleDbType.VarChar);
   objCmd.Parameters.Add(parm[0]);
   parm[1]=new OleDbParameter("@xm", OleDbType.VarChar);
   objCmd.Parameters.Add(parm[1]);
   parm[2]=new OleDbParameter("@xbmc",OleDbType.VarChar);
   objCmd.Parameters.Add(parm[2]);
   parm[3]=new OleDbParameter("@yhid",OleDbType.VarChar);
   objCmd.Parameters.Add(parm[3]);
  }
  catch(Exception ex)
  {
   MessageBox.Show(ex.ToString());
  }
  //遍歷DataTable將數據插入新建的Excel文件中
  for(int i=0;i<dt.Rows.Count;i++)
  {
   parm[0].Value=i+1;
   for(int j=1;j<parm.Length;j++)
   {
    parm[j].Value =dt.Rows[i][j];
   }
   objCmd.ExecuteNonQuery();
   rowRead++;
   percent=((float)(100*rowRead))/totalCount;
   //this.FM.CaptionText.Text = "正在導出數據,已導出[" + percent.ToString("0.00") + "%]...";
   if(i==dt.Rows.Count-1)
    //this.FM.CaptionText.Text = "請稍後......";
    System.Windows.Forms .Application.DoEvents();
  }
  objConn.Close();
 }
   
 //this.FM.CaptionText.Text = "";
}



方法三:


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();

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