• 爱情文章
  • 亲情文章
  • 友情文章
  • 生活随笔
  • 校园文章
  • 经典文章
  • 人生哲理
  • 励志文章
  • 搞笑文章
  • 心情日记
  • 英语文章
  • 范文大全
  • 作文大全
  • 新闻阅读
  • 当前位置: 山茶花美文网 > 范文大全 > 正文

    asp.net读取excel文件【asp.net中导出excel数据的方法汇总】

    时间:2020-05-27来源:山茶花美文网 本文已影响 山茶花美文网手机站

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

    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-->确定(如下图);

    在选择时注意一下.NET组件的版本号,图是的12.0.0.0是Office2007的版本:

    二、在项目中使用Microsoft.Office.Interop.Excel:

    如果想使用Microsoft.Office.Interop.Excel,首先需要在项目中引用命名空间:

    using Microsoft.Office.Interop.Excel;

    三、建立Excel.Application相关对象

    //建立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);//设置颜色

    ⑥、删除一行:

    //首先获取要删除的行的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 进程

    关于这方面内容有好多网友都在讲多种方法,经过本人实践,以下方面才能真正做到结束EXCEL的任务进程:

    1、将所有以上对EXCEL的操作放到一个方法中,

    2、在操作EXCEL后,即时将不使用对象一一释放并赋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的业务写在一个程序块中,“GC”是永远不能结束EXCEL进程的,在WEB应用程序中,这种现象是很可怕的事情。原因是GC不会清理本程序块中的垃圾内存的。

    4、在业务事件中调用killEXCEL()方法:

    protected void LinkButton3_Click(object sender, EventArgs e)

    {

    //导出EXCEL

    killExcel();

    }

    八、一些权限的基本设置:

    使用以上方法在开发环境中调试程序没有一点问题,等发布到服务器上后,程序还是不能正常运行,需要进行如下的权限设置:

    1、.NET导出Excel遇到的80070005错误的解决方法:

    检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046}的组件时失败,原因是出现以下错误: 80070005基本上.net导出excel文件,都需要如此配置一下,不配置有的时候没错,而配置后基本应该不会出错。

    具体配置方法如下:

    1:在服务器上安装office的Excel软件.

    2:在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"

    3:依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"

    4:在"DCOM配置"中找到"Microsoft Excel 应用程序",在它上面点击右键,然后点击"属性",弹出"Microsoft Excel 应用程序属性"对话框

    5:点击"标识"标签,选择"交互式用户"

    6:点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加一个"NETWORK SERVICE"用户(注意要选择本计算机名),并给它赋予"本地启动"和"本地激活"权限.

    7:依然是"安全"标签,在"访问权限"上点击"自定义",然后点击"编辑",在弹出的"安全性"对话框中也填加一个"NETWORK SERVICE"用户,然后赋予"本地访问"权限.

    8.如果交互式用户设置后出现错误8000401a,可取消交互式用户,指定为administratr,可暂时解决此问题。进一步的解决方式还有待探讨。

    9.采用第8点的设置后,打开Excel可能会出现“无法使用对象引用或链接”,并且不能进行单元格粘贴。原因不明,取消设置后即可消失。

    以上是本人在近期作开发时的一点心得,现整理成文档,供奋战在程序开发一线的朋友共享,愿看到的网友能名帮助解决“无法使用对象引用或链接”的问题。

    • asp.net读取excel文件【asp.net中导出excel数据的方法汇总】 相关文章:
    • 爱情文章
    • 亲情文章
    • 友情文章
    • 随笔
    • 哲理
    • 励志
    • 范文大全