C#Excel导入和导出

Excel导入

一、在WEB中导入Excel的方法

方法1: 通过OleDB方式获取Excel文件的数据到DataSet中,然后将Dataset中的每笔记录插入到SQL Server

using System.Data.OleDb;
using System.Data.SqlClient;

第一步:首先上传到服务器
  DataTable dt = new DataTable();
string strFileNewName = DateTime.Now.ToString(“yyyyMMddhhmmss”) + “.xls”;
FileUpload1.SaveAs(Server.MapPath(“Excel/Upload/” + strFileNewName));
第二步:将Excel的内容导入到DataTable中
using (OleDbConnection conn = new OleDbConnection(“Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =” + Server.MapPath(“Excel/Upload/” + strFileNewName) + “;Extended Properties=Excel 8.0″))
            {
                OleDbDataAdapter da = new OleDbDataAdapter(“select * from [sheet1$]“, conn);
                da.Fill(dt);
            }
第三步:将Datatable中的内容逐条插入到数据库中
            using (SqlConnection SqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ToString()))
            {
                SqlConn.Open();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string workno = dt.Rows[i]["工号"].ToString();
                    string username = dt.Rows[i]["姓名"].ToString();
                    string sex = dt.Rows[i]["性别"].ToString();
                    SqlCommand cmd = new SqlCommand(“insert into employees(workno,empname,sex) values(‘” + workno + “‘,’” + username + “‘,’” + sex + “‘)”, conn);
                    cmd.ExecuteNonQuery();
                }
            }
            Response.Write(“<script language=’javascript’>alert(‘文件上传成功!’);</script>”);
        }
 
缺点:如果要插入的记录很多,打开关闭数据库的次数会是个天文数字。  

二、在winform中导入Excel的方法
由于在windows中没有现成的upload控件可以使用,那么就自己造一个吧。
一个TextBox,一个Button,一个OpenFileDialog,你点Button,触发事件里把
if(OpenFileDialog.ShowDialog()==DialogResult.OK)
{
TextBox.Text = OpenFileDialog.FileName;
//之后想干吗就干吗
}
openFileDialog的Filter属性可以设置成 “Excel 文件|*.xls”;

Excel导出
在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件流输出写给浏览器。在Response输出时,t分隔的数据,导出Excel时,等价于分列,n等价于换行
1、将整个html全部输出Excel
此法将html中所有的内容,如按钮,表格,图片等全部输出到Excel中
     Response.Clear();    
    Response.Buffer=true;    
    Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");          
    Response.ContentEncoding=System.Text.Encoding.UTF8;  
    Response.ContentType   =   "application/vnd.ms-excel";  
    this.EnableViewState   =   false; 
这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们也可以输出(导出)图片、word文档等。下面的方法,也均用了这个属性。
注意:此方法确实可以导出excel,但更改ContentType的属性依然导出excel,我的测试环境是WPS Office 2010个人版,搜狗浏览器。
2、将GridView控件中的数据导出Excel   (指定控件导出方式,这里我以GridView为例子,大家可以使用任意控件)
上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,GridView控件上的数据。
System.Web.UI.Control ctl=this.GridView1;
//DataGrid1是你在窗体中拖放的控件
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";
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();
如果你的DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。而不是你select语句的全部信息。
注意:此法总是报错,提示gridview应该包含在runat标记内。

3、将DataSet中的数据导出Excel
有了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。那么把DataSet中的数据导出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。说明:参数ds应为填充有数据表的DataSet,文件名是全名,包括后缀名,如Excel2006.xls
public void CreateExcel(DataSet ds, string FileName)
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
            string colHeaders = "", ls_item = "";

            //定义表对象与行对象,同时用DataSet对其值进行初始化
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            int cl = dt.Columns.Count;

            //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列,加n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息

            //逐行处理数据  
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据    
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列,加n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                resp.Write(ls_item);
                ls_item = "";

            }
            resp.End();
        }

4、将dataview导出excel
若想实现更加富于变化或者行列不规则的excel导出时,可用本法
public void OutputExcel(DataView dv,string str)
{
   //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();
}
二、winForm中导出Excel的方法:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
    SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
    DataSet ds=new DataSet();
    da.Fill(ds,"table1");
    DataTable dt=ds.Tables["table1"];
    string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
    FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
    StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
    sw.WriteLine("自动编号,姓名,年龄");
    foreach(DataRow dr in dt.Rows)
    {
     sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
    }
    sw.Close();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
    Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
    Response.WriteFile(name); // 把文件流发送到客户端
    Response.End();

public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];

sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//定义一个新的工作簿
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
//命名该sheet
oSheet.Name="Sheet1";

oCells=oSheet.Cells;
//调用dumpdata过程,将数据导入到Excel中去
DumpData(dt,oCells);
//保存
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//退出Excel,并且释放调用的COM资源
oExcel.Quit();

GC.Collect();
KillProcess("Excel");
}

private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打开的进程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}
2、方法2:

protected void ExportExcel()
   {
    gridbind();
    if(ds1==null) return;

    string saveFileName="";
//    bool fileSaved=false;
    SaveFileDialog saveDialog=new SaveFileDialog();
    saveDialog.DefaultExt ="xls";
    saveDialog.Filter="Excel文件|*.xls";
    saveDialog.FileName ="Sheet1";
    saveDialog.ShowDialog();
    saveFileName=saveDialog.FileName;
    if(saveFileName.IndexOf(":")<0) return; //被点了取消
//    excelapp.Workbooks.Open   (App.path & 工程进度表.xls)
  
    Excel.Application xlApp=new Excel.Application();
    object missing=System.Reflection.Missing.Value;

    if(xlApp==null)
    {
     MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
     return;
    }
    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;
   

    string oldCaption=Title_label .Text.Trim ();
    long totalCount=ds1.Tables[0].Rows.Count;
    long rowRead=0;
    float percent=0;

    worksheet.Cells[1,1]=Title_label .Text.Trim ();
    //写入字段
    for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
    {
     worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
     range=(Excel.Range)worksheet.Cells[2,i+1];
     range.Interior.ColorIndex = 15;
     range.Font.Bold = true;

    }
    //写入数值
    Caption .Visible = true;
    for(int r=0;r<ds1.Tables[0].Rows.Count;r++)
    {
     for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
     {
      worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];    
     }
     rowRead++;
     percent=((float)(100*rowRead))/totalCount;   
     this.Caption.Text= "正在导出数据["+ percent.ToString("0.00") +"%]";
     Application.DoEvents();
    }
    worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
  
    this.Caption.Visible= false;
    this.Caption.Text= oldCaption;

    range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
    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;

    if(ds1.Tables[0].Columns.Count>1)
    {
     range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
     }
    workbook.Close(missing,missing,missing);
    xlApp.Quit();
   }

3.从DataGridView里导出
/// <summary>  
        /// 常用方法,列之间加\t开。  
        /// </summary>  
        /// <remarks>  
        /// using System.IO;  
        /// </remarks>  
        /// <param name="dgv"></param>  
        private void DataGridViewToExcel(DataGridView dgv)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.CheckFileExists = false;
            dlg.CheckPathExists = false;
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";
                try
                {
                    //写入列标题  
                    for (int i = 0; i < dgv.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            columnTitle += "\t";
                        }
                        columnTitle += dgv.Columns[i].HeaderText;
                    }
                    sw.WriteLine(columnTitle);

                    //写入列内容  
                    for (int j = 0; j < dgv.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dgv.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                columnValue += "\t";
                            }
                            if (dgv.Rows[j].Cells[k].Value == null)
                                columnValue += "";
                            else
                                columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                        sw.WriteLine(columnValue);
                    }
                    sw.Close();
                    myStream.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
4.把Excel数据读到DataSet里
OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.CheckFileExists = false;
            dlg.CheckPathExists = false;
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.Title = "将Excel文件数据导入到DataSet";
            dlg.ShowDialog();

            DataSet ds = new DataSet();
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dlg.FileName.Trim() + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
            using (OleDbConnection OleConn = new OleDbConnection(strConn))
            {
                OleConn.Open();
                String sql = "SELECT * FROM [Sheet1$]";
                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                OleDaExcel.Fill(ds);
                OleConn.Close();
            }
三 字符串导出方法

1.一个通用的导出Excel的方法

/// <summary>       
/// 导出Execel       
/// </summary>       
/// <param name="columnTitle">列名以"\t分隔"如 列2\t列3\t列4</param>       
/// <param name="resutl">行,要与上面的列对应,列名以"\t分隔"如 列2\t列3\t列4 第行使用\n分隔 </param>       
private void ToExcel(string columnTitle, string resutl)       

 {           

          SaveFileDialog dlg = new SaveFileDialog();           

          dlg.Filter = "Execl files (*.xls)|*.xls";           

          dlg.FilterIndex = 0;           

          dlg.RestoreDirectory = true;           

          dlg.Title = "保存为Excel文件";           

          if (dlg.ShowDialog() == DialogResult.OK)           

          {               

                  Stream myStream;               

                  myStream = dlg.OpenFile();               

                  StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));               

                  try               

                  {                   

                           //写入列名称                   

                          sw.WriteLine(columnTitle);                   

                          //写入行                   

                          sw.WriteLine(resutl);                                       

                          sw.Close();                   

                         myStream.Close();               

                  }               

                  catch (Exception e)               

                  {                   

                         MessageBox.Show(e.ToString());               

                  }               

                  finally               

                  {                   

                         sw.Close();                   

                 myStream.Close();               

                 }           

       }       

}
四、附注:
虽然都是实现导出excel的功能,但在asp.net和winform的程序中,实现的代码是各不相同的。在asp.net中,是在服务器端读取数据,在服务器端把数据以ms-excel的格式,以Response输出到浏览器(客户端);而在winform中,是把数据读到客户端(因为winform运行端就是客户端),然后调用客户端安装的office组件,将读到的数据写在excel



-------------------------------------------------------------------------
备注:可以将内存中的DataTable导出到Excel中,对分页的情况同样有效。
public void DataTable2Excel(DataTable dt)
        {
            //dt.Columns[0].ColumnName = "姓名"; //如果需要,可以将datatable中的英文标题改成中文
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
            HttpContext curContext = System.Web.HttpContext.Current;
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.Default;
            curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
            curContext.Response.Charset = "";
            curContext.Response.Write(BuildExportHTML(dt));//在Excel文件中写入数据
            curContext.Response.Flush();
            curContext.Response.End();
        }
       
        private static string BuildExportHTML(DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;
            int pagerecords = 5000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";
            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }


以下代码只能导出当前页,如果分页的话,其他页无法导出,以后研究下怎样解决此问题。
this.UltraWebGridExcelExporter1.DownloadName = DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";              
Infragistics.Excel.Workbook workbook = new Infragistics.Excel.Workbook(); //创建新的Excel文件
workbook.Worksheets.Add("Sheet1"); //创建新的工作薄
this.UltraWebGridExcelExporter1.Export(this.UltraWebGrid1, workbook);//将表格显示数据导出到Excel文件中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值