Loading [MathJax]/jax/input/TeX/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >关于asp.net与winform导出excel的代码

关于asp.net与winform导出excel的代码

作者头像
跟着阿笨一起玩NET
发布于 2018-09-19 03:47:24
发布于 2018-09-19 03:47:24
5.6K00
代码可运行
举报
运行总次数:0
代码可运行

一、asp.net中导出Execl的方法: 在asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件输出流写给浏览器。在Response输出时,t分隔的数据,导出execl时,等价于分列,n等价于换行。 1、将整个html全部输出execl 此法将html中所有的内容,如按钮,表格,图片等全部输出到Execl中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    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文档等。下面的方法,也均用了这个属性。 2、将DataGrid控件中的数据导出Execl 上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,DataGrid控件上的数据。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
System.Web.UI.Control ctl=this.DataGrid1;
 //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语句的全部信息。 为方便使用,写成方法如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void DGToExcel(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";
    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(); 
 }

   用法:DGToExcel(datagrid1); 3、将DataSet中的数据导出Execl 有 了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。那么把DataSet中的数据导出,也就是把DataSet中的 表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。说明:参数ds应为填充有数据表的DataSet,文件名是全 名,包括后缀名,如execl2006.xls

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制

 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);    
 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导出execl 若想实现更加富于变化或者行列不规则的execl导出时,可用本法。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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(); 
 }

   上面的方面,均将要导出的execl数据,直接给浏览器输出文件流,下面的方法是首先将其存到服务器的某个文件夹中,然后把文件发送到客户端。这样可以持久的把导出的文件存起来,以便实现其它功能。 5、将execl文件导出到服务器上,再下载。 二、winForm中导出Execl的方法: 1、方法1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
   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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制

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

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

asp.net导出Excel/Csv格式数据最优方案(C#)

好久没有写点什么了,也许是太忙。一年了,积累了不少好的东东,有机会时就写出来与大家分享。

好,言归正传。 导出到Excel/Csc文件并不难,所以就有好多方法:控件直接Render、把DataSet输出成String再Write出来等,(当然如果调用Excel程序的库文件的话还可以使用更强的直接操作Excel的方法,但这种方法用于Web服务显得有点要求太高:必须让Web服务器安装指定版本的Excel或其支持库文件)。就其前两种方法,实际上也是一样的,Render也是把由DataSet转变的View生成为一个Table输出到客户端而已,只不过隐藏了细节,如果不信,你用EditPlus什么的看看生成的.xls文件就知道了。

Excel的识别力太强了,以至于它本身的格式、Csv格式、Tab分隔符格式、网页的Table格式等都能够很好的打开。但是它“太聪明”了,以至于自动识别数字和字符串,而且要把超过11位的数字自动变为科学计数法的格式,你试试输入“123456789012”,离开那个单元格,就成“123457E+11”了,够聪明的吧,不过有时会让我们感觉不便,因为我输入的就是我自己的身份证号码,尾巴上没有“X”,本来好好的15位数字,得现在成这么个计数法了。那我就改改显示格式吧,改为把数字显示为文本,好了。可是国家的身份证升级了,号码变成18位,我把它输入到数据库,导出来时,用刚才的方法处理过,18位没错,可是最后三位怎么都是零了!Excel为我们做了太多的事,不管是应该的还是不应该的。

怎么解决?请看代码:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public static string ExportTable(DataSet ds)
     {
         string data = "";
         //data = ds.DataSetName + "\n";
        foreach (DataTable tb in ds.Tables)
         {
             //data += tb.TableName + "\n";
             data += "<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">";
             //写出列名
             data += "<tr style=\"font-weight: bold; white-space: nowrap;\">";
             foreach (DataColumn column in tb.Columns)
             {
                 data += "<td>" + column.ColumnName + "</td>";
             }
             data += "</tr>";
            //写出数据
             foreach (DataRow row in tb.Rows)
             {
                 data += "<tr>";
                 foreach (DataColumn column in tb.Columns)
                 {
                     if (column.ColumnName.Equals("证件编号") || column.ColumnName.Equals("报名编号"))
                         data += "<td style=\"vnd.ms-excel.numberformat:@\">"+ row[column].ToString() + "</td>";
                     else 
                         data += "<td>" + row[column].ToString() + "</td>";
                 }
                 data += "</tr>";
             }
             data += "</table>";
         }
        return data;
     }

     public static void ExportDsToXls(Page page, string sql)
     {
         ExportDsToXls(page, "FileName", sql);
     }
     public static void ExportDsToXls(Page page, string fileName, string sql)
     {
         DataSet ds = DBUtil.GetDataSet(sql);
         if (ds != null) ExportDsToXls(page, fileName, ds);
     }
     public static void ExportDsToXls(Page page, DataSet ds)
     {
         ExportDsToXls(page, "FileName", ds);
     }
     public static void ExportDsToXls(Page page, string fileName, DataSet ds)
     {
         page.Response.Clear();
         page.Response.Buffer = true;
         page.Response.Charset = "GB2312";
         //page.Response.Charset = "UTF-8";
         page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".xls");
         page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
         page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
         page.EnableViewState = false;
         page.Response.Write(ExportTable(ds));
         page.Response.End();
     }
 //style="vnd.ms-excel.numberformat:@" 可以去除自动科学计数法的困扰 
 //输出为Table,能够最大限度的减少字段中数据对生成的文件格式的影响,在这里我没有处理数据中含有HTML标签的情况 在页面后台中,这样使用就可以了:
    protected void lbtnToExcel_Click(object sender, EventArgs e)
     {
         string strWhere = BuildSearchWhereString(); 
         string strOrder = this.hidOrderString.Value; 
         string sql = "SELECT 报名编号, 证件编号, 姓名, 考区考点, 报考类别, " 
             + "行政区划名称 AS 行政区划, 单位名称 AS 工作单位, 毕业学校名称, 毕业专业名称 AS 毕业专业, 毕业年月, " 
             + "通讯地址, 性别"
             + " from [VW报名]"; 
         if (!string.IsNullOrEmpty(strWhere)) sql += " where " + strWhere; 
         if (!string.IsNullOrEmpty(strOrder)) sql += " order by " + strOrder; 
         else sql += " order by [报考类别]";
         PageExport.ExportDsToXls(this.Page, "BaoMing", sql);
         dataBind();
     }

其中在引入dll时 注意其版本,具体各个版本可以到我的资源下载地址http://download.csdn.net/detail/haiziguo/4469170

本次用到的dataset导入到excel中的代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public static void ToManySheetExl(DataSet ds, string strExcelFileName,Page page)
    {
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        string path = "";
        if (excel == null)
        {
            MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
            return;
        }
        try
        {
            excel.Visible = false;
            //设置禁止弹出保存和覆盖的询问提示框
            excel.DisplayAlerts = false;
            excel.AlertBeforeOverwriting = true;
            //增加一个工作簿
            Workbook book = excel.Workbooks.Add(true);
            //添加工作表         其中ds.Tables.Count.ToString()为要创建的sheet的个数
            Worksheet sheets = (Microsoft.Office.Interop.Excel.Worksheet)
                book.Worksheets.Add(Missing.Value, Missing.Value, Convert.ToInt32(ds.Tables.Count.ToString()), Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            //开始遍历ds中的各个dataTable
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                System.Data.DataTable table = ds.Tables[i];
                //HttpContext.Current.Response.Write(ds.Tables[0].Rows[0][0].ToString() + "<p/>");
                //获取一个工作表
                Worksheet sheet = book.Worksheets[i + 1] as Worksheet;
                int rowIndex = 1;
                int colIndex = 0;
                //为各个sheet添加列名
                foreach (DataColumn col in table.Columns)
                {
                    colIndex++;
                    sheet.Cells[1, colIndex] = col.ColumnName;
                }
                //开始添加数据
                foreach (DataRow row in table.Rows)
                {
                    rowIndex++;
                    colIndex = 0;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        //在这里要在数字前加前单引号
                        String typeName = row[col.ColumnName].GetType().ToString();
                        sheet.Cells[rowIndex, colIndex] = typeCheckAdd(row[col.ColumnName].ToString(), typeName);
                    }
                }
                //将各个sheet的名字改为datatable.TableName
                sheet.Name =ds.Tables[i].TableName.ToString();
            }

            //删除多余Sheet
            for (int g = 1; g <= book.Worksheets.Count; g++)
            {
                Worksheet sheet = book.Worksheets[g] as Worksheet;
                if (Convert.ToInt32(sheet.Name.Length.ToString())>5&&sheet.Name.Substring(0, 5) == "Sheet")
                {
                    sheet.Delete();
                    g--;
                }
            }
            path = page.Server.MapPath("../") + @"9_Tool/" + strExcelFileName + ".xls";

            //book.Save();
            book.SaveAs(path, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
	   book.close();//很多网站没有用这个方法,让我找了半天 不知道错误在哪里
            //book.SaveAs(strExcelFileName);

            excel.Quit();
            excel = null;
            GC.Collect();
            FileStream fs = new FileStream(path, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            File.Delete(path);
            page.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            page.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmssffff") + "客服审评表.xls"));
            page.Response.BinaryWrite(bytes);
            page.Response.Flush();
            page.Response.End();        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
    #region 若是大数需加前导引号变成字符串
    public static String typeCheckAdd(String cellContent, String strType)
    {
        String cellContentAdd;
        
        switch (strType)
        {
            case "System.Int64":
                cellContentAdd = "'" + cellContent;
                break;
            case "System.DateTime":
                cellContentAdd = (Convert.ToDateTime(cellContent)).ToString("yyyy-MM-dd"); 
                break;
            default:
                cellContentAdd = cellContent;
                break;
        }
        return cellContentAdd;
    }
    #endregion
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012-08-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
asp.net里导出excel表方法汇总
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;
全栈程序员站长
2022/06/30
8840
把图片插入excel表格并按分类生成sheets
private void Excel_Click(object sender, System.EventArgs e)
Java架构师必看
2021/03/22
9270
C# 实现完善 Excel 不规则合并单元格数据导入
在我的文章 《C#实现Excel合并单元格数据导入数据集》里讲述了可以将具有合并单元格的Excel文件数据导入到DataSet里,在实际使用情况中遇到如下情况,如下图:
初九之潜龙勿用
2025/02/20
1570
C# 实现完善 Excel 不规则合并单元格数据导入
C#导入导出数据到Excel的通用类代码
Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library
用户8671053
2021/11/03
8890
Excel导入导出数据库02
excel导入时还要保存字体、其背景颜色等信息时读取方法就要改变: 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Data.OleDb; 7 using System.Data; 8 using Microsoft.Office.Interop.Excel; 9 u
欢醉
2018/01/22
4.4K0
C# excel文件导入导出
在C#交流群里,看到很多小伙伴在excel数据导入导出到C#界面上存在疑惑,所以今天专门做了这个主题,希望大家有所收获!
zls365
2020/08/19
3.9K0
C# excel文件导入导出
C# 实现二维数据数组导出到 Excel
将数据库查询出来的数据导出并生成 Excel 文件,是项目中经常使用的一项功能。本文将介绍通过数据集生成二维数据数组并导出到 Excel。
初九之潜龙勿用
2024/09/11
1930
C# 实现二维数据数组导出到 Excel
DataGridView输出或保存为Excel文件(支持超过65536行多Sheet输出)
/// <summary>         /// DataGridView控件数据导出到Excel,可设定每一个Sheet的行数         /// 建立多个工作表来装载更多的数据         /// </summary>         /// <param name="ExportGrid">DataGridView控件</param>         /// <param name="fullFileName">保存的文件路径</param>         /// <param name=
跟着阿笨一起玩NET
2018/09/18
1.5K0
常用Excel导出方法
  最近项目中用到导出Excel,项目已有的方法1和2,导出的excel,看似是exce格式,其实只是改了后缀名。
_一级菜鸟
2020/04/08
7500
常用Excel导出方法
C# 读取EXCEL文件的三种经典方法
1.方法一:采用OleDB读取EXCEL文件: 把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下:
代码伴一生
2021/09/22
2.5K0
C# 实现格式化文本导入到Excel
在一些导入功能里,甲方经常会给我们一些格式化的文本,类似 CSV 那样的纯文本。比如有关质量监督的标准文件(如国家标准、地方标准、企业标准等),还有一此国际标准文件等等。提供给我们的这些文件是文件尺寸比较大的纯文本文件,文件内容是格式化的文本,具有规律的分隔字符。Excel 本身提供有导入文本文件的功能,但由于标准制定和发布是比较频繁,每次的导入与整理还是比较耗时的,因些实现文本文件导入到 Excel 的功能可以更快速的解决重复劳动和错误,实现流程自动化的一环。
初九之潜龙勿用
2024/06/20
1210
C# 实现格式化文本导入到Excel
GridView导出Excel的超好样例「建议收藏」
事实上网上有非常多关于Excel的样例,可是不是非常好,他们的代码没有非常全,读的起来还非常晦涩。经过这几天的摸索,最终能够完毕我想要导出报表Excel的效果了。以下是我的效果图。
全栈程序员站长
2022/09/07
1K0
GridView导出Excel的超好样例「建议收藏」
C#向excel中写入数据的三种方式
第一种:将DataGrid中的数据以流的形式写到excel中,格式以html的形式存在             Response.Clear();             Response.Buffer = true;             Response.Charset = "GB2312";             Response.AppendHeader("Content-Disposition", "attachment;filename=DialoutTemplate.xls");     
岑玉海
2018/02/28
4K0
vb.net ExcelHelper类(三)
Public Sub InsertRows(rowIndex As Integer, count As Integer)
办公魔盒
2019/07/22
1K0
C#实现Excel模板导出和从Excel导入数据
      午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.
用户1055830
2018/01/18
4.2K0
C#实现Excel模板导出和从Excel导入数据
免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)
彭泽0902
2018/01/04
4.8K0
免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)
DataTable导入到Excel文件
public static bool DataTableToExcel(System.Data.DataTable dt, string fileName, bool showFileDialog=false)         {             if (showFileDialog)             {                 SaveFileDialog saveFileDialog = new SaveFileDialog();                 saveFile
跟着阿笨一起玩NET
2018/09/18
1.6K0
.Net之Nopi Excel数据导出和批量导入功能
  它是一个专门用于读写Microsoft Office二进制和OOXML文件格式的.NET库,我们使用它能够轻松的实现对应数据的导入,导出功能,并且还能通过其对应的属性对Excel进行对应的样式调整。是一个简洁而又强大的第三方库。
追逐时光者
2019/08/28
1.7K0
.Net之Nopi Excel数据导出和批量导入功能
C# NPOI导出Excel和EPPlus导出Excel比较[转]
在类库References右键Manage NuGet Packages...,之后选择添加对应的dll。
谭广健
2019/04/02
4.4K0
ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出
昨天文章太过仓促没有补充导出的示例源码,在者当时弄到到很晚没时间做出导出功能,对阅读理解造成影响,现补充一份示例源码,顺便补充导出的功能说明,望理解 示例代码下载   https://yunpan.cn/cRTHt5MuKavwH 访问密码 0a47 ps:Vs数据库脚本在解压目录下,修改web.config数据库链接,示例代码包含:导入,导出,上传 前言: 导入导出实在多例子,很多成熟的组建都分装了导入和导出,这一节演示利用LinqToExcel组件对Excel的导入,这个是一个极其简单的例子。
用户1149182
2018/01/16
1.9K0
ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出
相关推荐
asp.net里导出excel表方法汇总
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验