Excel相关操作(转)

NPOI控件

在页面上点击服务器按钮输出Excel只能输出一次(第二次点击按钮无反应):

 添加以下js:

<script type='text/javascript'>  

     _spOriginalFormAction = document.forms[0].action;   

      _spSuppressFormOnSubmitWrapper=true;   

</script>  

 

 

转自:

http://www.cnblogs.com/stswordman/archive/2006/08/24/485641.html

http://www.cnblogs.com/xiaotao823/archive/2008/09/26/1299364.html

C# 将数据导出到Excel汇总

一、asp.net中导出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文档等。下面的方法,也均用了这个属性。

2、将DataGrid控件中的数据导出Excel

上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,DataGrid控件上的数据。
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语句的全部信息。

为方便使用,写成方法如下:
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);
  

并且还需要override一下VerifyRenderingInServerForm方法(这一点非常重要,否则在点击按钮后会报错,译者注)代码如下:

public override void VerifyRenderingInServerForm(Control control)

{

}

个人补充:

如果在UserControl中使用的时候,无法执行VerifyRenderingInServerForm的时候,可以使用这个方式:

public static void ToExcelJT(System.Web.UI.Page page, DataTable tab, string FileName)
        {
            System.Web.HttpResponse httpresponse = page.Response;
            System.Web.UI.WebControls.DataGrid datagrid = new System.Web.UI.WebControls.DataGrid();
            datagrid.DataSource = tab.DefaultView;
            datagrid.AllowPaging = false;
            datagrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
            datagrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            datagrid.HeaderStyle.Font.Bold = true;
            datagrid.DataBind();

            HttpContext.Current.Response.Charset = "UTF-8";
            //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            datagrid.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }

 

即:根据DataTable重新生成Grid。
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);   
 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();
}

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

二、winForm中导出Excel的方法:

1、方法1:

   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 Idea [I].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();
  }

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

GridView导出Excel研究

Introduction:

GridView中的数据导出为Excelweb应用中的常见功能。在不同的应用场景下有不同的导出技术。在本文中我将介绍一些导出的技术,希望对您有所帮助

GridView Export the Excel (Basic Code): 

.

首先看一个基础的应用。创建一个表格,见截图


 

然后将数据库中的数据绑定到GridView中的数据,代码如下:

private void BindData()

{

SqlConnection myConnection = new SqlConnection("Server=localhost;Database=School;Trusted_Connection=true");

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Users", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

gvUsers.DataSource = ds;

gvUsers.DataBind();

}


现在,GridView中已经绑定了数据,接下来的任务就是导出到Excel。下面是button事件中的代码

Response.ClearContent();

Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

并且还需要override一下VerifyRenderingInServerForm方法(这一点非常重要,否则在点击按钮后会报错,译者注)代码如下:

public override void VerifyRenderingInServerForm(Control control)

{

}

点击导出按钮后会弹出对话框,询问您打开或保存。选择打开文件,导出到Excel的结果如下图:


Exporting GridView to Excel With Style:

您是否注意到了以上代码存在一些的问题?是的,ID列开头的0都被截去了。如果你的ID000345,导出后就编程了345。这个问题可以通过把css添加到输出流中来解决。为了使ID列正确显示,您需要将其储存为文本格式。Excel中的文本格式表示为"mso-number-format:"\@"

protected void Btn_ExportClick(object sender, EventArgs e)

{

string style = @"<style> .text { } </script> ";

Response.ClearContent();

Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);

// Style is added dynamically

Response.Write(style);

Response.Write(sw.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)

{

}

 在上面的代码中,我通过”style”变量来控制GridView列的样式。并通过Respnose.Write方法将其添加到输出流中。最后把样式添加到ID列。这一步需要在RowDataBound事件中完成

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)

 

 

有个开源的控件 NPOI - 一个能帮助你直接读写office文件流的库 (QQ交流群: 124527967)

http://npoi.codeplex.com/

教程地址NPOI 1.2教程(目录)

 

 

部分介绍C#操作excel(NPOI篇) http://www.cnblogs.com/MR_ke/archive/2010/02/25/1673243.html

 

 

 

 

使用JavaScript复制表格进Excel

 

 

<script type="text/javascript">
function toExcel(tablename) //导出到excel
{
//    var mysheet=new ActiveXObject("OWC.Spreadsheet");
//    with(mysheet)
//    {
//        DataType = "HTMLData";
//        HTMLData =tablename.outerHTML;
//        try
//        {
//            ActiveSheet.Cells(1,1).value="";
//            ActiveSheet.Cells(2,1).value="";
//            // ActiveSheet.Cells(34,1).value="导出完毕";
//            ActiveSheet.Export("导出.xls", 0);
//            alert('导出完毕');
//        };
//        catch (e)
//        {
//            alert('导出Excel表失败,请确定已安装Excel2000(或更高版本),并且没打开同名xls文件');
//        };
//    }
    var curTbl = document.getElementById(tablename);
    var oXL = new ActiveXObject("Excel.Application");
    var oWB = oXL.Workbooks.Add();
    var oSheet = oWB.ActiveSheet;
    var sel = document.body.createTextRange();
    sel.moveToElementText(curTbl);
    sel.select();
    sel.execCommand("Copy");
    oSheet.Paste();
    oXL.Visible = true;

}

</script>

 

 string toExcel = "javascript:toExcel('tbKPI');return false;";
btnExport.Attributes["onclick"] = toExcel;

 

注意信任级别

 

 

 

 

一.导入导出excel常用方法:

1.用查询表的方式查询并show在数据集控件上。

ExpandedBlockStart.gif 代码
 
   
public static string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.xls;Extended Properties=Excel 8.0 " ;
public static DataSet ds;
protected void Page_Load( object sender, EventArgs e)
{

OleDbConnection conn
= new OleDbConnection(strCon);
string sql = " select * from [Sheet1$] " ;
conn.Open();
OleDbDataAdapter myCommand
= new OleDbDataAdapter(sql, strCon);
ds
= new DataSet();
myCommand.Fill(ds,
" [Sheet1$] " );
conn.Close();
datagrid1.DataMember
= " [Sheet1$] " ;
datagrid1.DataSource
= ds;
datagrid1.DataBind();


// Excel.Application excel = new Excel.Application();
// excel.Application.Workbooks.Add(true);
// excel.Visible = true;
}

 

2.一个一个单元格的进行插入

 

ExpandedBlockStart.gif 代码
 
   
1 string str = @" Data Source=IT-428E4EA4B0C7\SQLEXPRESS;Initial Catalog=TestBase;Integrated Security=True " ;
2 SqlConnection conn = new SqlConnection(str);
3 conn.Open();
4 int n = 0 ;
5 for ( int i = 1 ; i < 20 ; i ++ )
6 {
7 if (n > 3 )
8 break ;
9 else
10 if (msheet.Cells.get_Range( " A " + i, Type.Missing).Text.ToString() == "" && n <= 3 )
11 { n ++ ; }
12 else
13 {
14   // 循环获取excel单元格的值一次一次的插入,excuteSql为执行的存储过程
15   excuteSql(msheet.Cells.get_Range( "B" + i, Type.Missing).Text.ToString(),
16 msheet.Cells.get_Range("B" + (i + 1
), Type.Missing).Text.ToString(),
17 msheet.Cells.get_Range("B" + (i + 2
), Type.Missing).Text.ToString(),
18
conn);
19 i = i + 3 ;
20
21 }
22 }
23
24 conn.Close();

二快速导入导出

1.我们都知道当向db里批量插入数据的时候我们会选择SqlBulkCopy

if (dataTable!=null && dataTable.Rows.Count!=0)
            {
                sqlBulkCopy.WriteToServer(dataTable);
            }
 

这个可以看 深山老林新发的一篇SQLServer中批量插入数据方式的性能对比下面是SqlBulkCopy的方法,这个方法有一个弊端就是当excel某一列即有文字,还有日期的时候,会出现null值,我在网上查了一些资料说连接字串加上;HDR=YES;IMEX=1'的时候会都当做字符处理,但是还是会出现一些bug,所以建议最好先把excel数据分析到datatable里然后再用SqlBulkCopy倒入数据库

  

 

ExpandedBlockStart.gif 代码
 
   
1 // block copy to DB from Excel
2 // By xijun,
3 // step 1 create an excel file C:\Inetpub\wwwroot\test.xls , fill cell(1,1) with "Data",cell(1,2) with "name"
4 // step 2 create table named "Data" with 2 column ("data","name") in your DB
5 // there the code below:
6 DateTime t1 = DateTime.Now;
7 Response.Write( " <br>start time: " + t1.ToString());
8 string ExcelFile = @" C:\\20090916_Hub_Report.xls " ;
9 string excelConnectionString = @" Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + ExcelFile + " ;Extended Properties='Excel 8.0;HDR=YES;IMEX=1' " ;
10
11 using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
12 {
13
14 excelConnection.Open();
15 // Getting source data
16 // 非空讀入數據
17 OleDbCommand command = new OleDbCommand( " Select [Region],[CustomerPN],[RMA],[Date],[QTY],[Return/Pull] FROM [20090916_Hub_Report$] " , excelConnection);
18 // Initialize SqlBulkCopy object
19
20 using (OleDbDataReader dr = command.ExecuteReader())
21 {
22 // Copy data to destination
23 string sqlConnectionString = @" Data Source=MININT-G87PHNA\SQLEXPRESS;Initial Catalog=GDS_Service;Integrated Security=True " ;
24 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
25 {
26 bulkCopy.DestinationTableName = " GDS_Hub_data " ;
27 // 加入只加入一個列的話,那么就會其他數據庫列都默認為空。
28 bulkCopy.ColumnMappings.Add( " Region " , " region " );
29 bulkCopy.ColumnMappings.Add( " CustomerPN " , " customer_item_number " );
30 bulkCopy.ColumnMappings.Add( " RMA " , " Rma " );
31 bulkCopy.ColumnMappings.Add( " Date " , " date " );
32 bulkCopy.ColumnMappings.Add( " QTY " , " Qty_1 " );
33 bulkCopy.ColumnMappings.Add( " Return/Pull " , " return_pull " );
34 // bcp.BatchSize = 100; // 每次传输的行数
35 // bcp.NotifyAfter = 100; // 进度提示的行数
36 bulkCopy.BatchSize = 100 ;
37 bulkCopy.NotifyAfter = 100 ;
38 bulkCopy.WriteToServer((IDataReader)dr);
39
40
41 }
42 }
43 // Closing connection
44 excelConnection.Close();
45 }
46
47 DateTime t2 = DateTime.Now;
48 Response.Write( " <br>End time: " + t2.ToString());
49 Response.Write( " <br>use time: " + ((TimeSpan)(t2 - t1)).Milliseconds.ToString() + " Milliseconds " );
50 Response.Write( " <br>inser record count :3307 " );

 2.快速导出db的数据到excel

这种方法就是利用

 Excel.QueryTables 
 Excel.QueryTable

Querytable把数据快速导入excel里。我们在做复杂报表的时候,这个用的是比较多了,但是单单会这个没有用,它只是快速的把db里的数据放放到excel里,

在做大量数据而且需要设定excel样式的时候我们会选择先用这种方法把数据导入excel一个临时sheet,再利sheet复制,sheet移动,和一些excel样式设定,以及

excel一个强大的自动填充的功能,那么这些就可以让我们快速的做出花样多试的excel报表,当然这个要求我们比较熟练office的操作,包括宏的操作。

ExpandedBlockStart.gif代码
 
   
1 public string query_table_getdata(string sourpath)
2
{
3 string str_path = sourpath.Substring(0, sourpath.Length - 22
);
4 str_path = str_path + "basic.xls"
;
5

6 Excel.QueryTables m_objQryTables = null ;
7 Excel.QueryTable m_objQryTable = null
;
8 Excel.Application m_objExcel = null
;
9 Excel.Workbooks m_objBooks = null
;
10 Excel.Workbook m_objBook = null
;
11 Excel.Sheets m_objSheets = null
;
12 Excel.Worksheet m_objSheet = null
;
13 Excel.Range m_objRange = null
;
14 m_objExcel = new
Excel.Application();
15

16 // try
17 //{

18 m_objBooks = m_objExcel.Workbooks;
19
m_objBooks.Open(sourpath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
20
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
21

22 m_objBook = (Excel.Workbook)m_objBooks.get_Item(1 );
23

24
25 m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
26 m_objSheet = (Excel.Worksheet)m_objSheets.get_Item(1
);
27 m_objRange = m_objSheet.get_Range("A2"
, Type.Missing);
28 m_objQryTables =
m_objSheet.QueryTables;
29 string sqlstr = "SELECT [day01],[day02],[day03],[day04],[day05],[day06],[day07],[day08],[day09],[day10],[day11],[day12],[day13],[day14]"
;
30 sqlstr += ",[week01] ,[week02],[week03],[week04],[week05],[week06],[week07],[week08],[week09],[week10],[week11],[week12],[week13],[week14]"
;
31 sqlstr += ",[week15],[week16],[week17],[week18],[week19],[week20],[week21],[week22],[week23],[week24]"
;
32 sqlstr += " FROM [GDS_Service].[dbo].[GDS_Service_Report_Base] order by groupID ,id"
;
33 //可以放在配置文件里

34 string conn = @"Provider=SQLOLEDB.1;Data Source=MININT-G87PHNA\SQLEXPRESS;uid=xijun_ke;Password=12345678;
Initial Catalog=GDS_Service;Persist Security Info=False;";
35

36 m_objQryTable = (Excel.QueryTable)m_objQryTables.Add("OLEDB;" + conn, m_objRange, sqlstr);
37

38 m_objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;
39

40 m_objQryTable.Refresh(false );
41
m_objBook.SaveAs(str_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
42 m_objBook.Close(false
, Type.Missing, Type.Missing);
43 //
}
44 //
catch (Exception ee)
45 //
{
46 //
mp.WriteLog(ee.ToString());
47 //
}
48 //
finally
49 //{

50 m_objExcel.Quit();
51
GC.Collect();
52 //}

53 return str_path;
54

55 }

com操作excel的一些特性操作:

 
  
range.NumberFormatLocal  =   " @ " ;      // 设置单元格格式为文本
range  =  (Range)worksheet.get_Range( " A1 " " E1 " );      // 获取Excel多个单元格区域:本例做为Excel表头
range.Merge( 0 );      // 单元格合并动作
worksheet.Cells[ 1 1 =   " Excel单元格赋值 " ;      // Excel单元格赋值
range.Font.Size  =   15 ;      // 设置字体大小
range.Font.Underline = true ;      // 设置字体是否有下划线
range.Font.Name = " 黑体 " ;     设置字体的种类
range.HorizontalAlignment
= XlHAlign.xlHAlignCenter;      // 设置字体在单元格内的对其方式
range.ColumnWidth = 15 ;      // 设置单元格的宽度
range.Cells.Interior.Color = System.Drawing.Color.FromArgb( 255 , 204 , 153 ).ToArgb();      // 设置单元格的背景色
range.Borders.LineStyle = 1 ;      // 设置单元格边框的粗细
range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb());      // 给单元格加边框
range.EntireColumn.AutoFit();      // 自动调整列宽
Range.HorizontalAlignment =  xlCenter;      //  文本水平居中方式
Range.VerticalAlignment =  xlCenter      // 文本垂直居中方式
Range.WrapText = true ;      // 文本自动换行
Range.Interior.ColorIndex = 39 ;      // 填充颜色为淡紫色
Range.Font.Color = clBlue;      // 字体颜色
xlsApp.DisplayAlerts = false ;      // 保存Excel的时候,不弹出是否保存的窗口直接进行保存
   workbook.SaveCopyAs(temp); /**/ /// 填入完信息之后另存到路径及文件名字

excel宏操作,sheet和单元格操作:

ExpandedBlockStart.gif 代码
 
   
1 /// <summary>
2 /// 讀取excel數據和插入公式
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 protected void Button2_Click( object sender, EventArgs e)
7 {
8 DateTime t1 = DateTime.Now;
9 Response.Write( " <br>start time: " + t1.ToString());
10 Excel.Application excelkk = new Excel.Application();
11
12 excelkk.Workbooks.Add( true );
13 int row = 2 ;
14 DataTable myTable = ds.Tables[ " [Sheet1$] " ];
15 for ( int i = 0 ; i < myTable.Columns.Count; i ++ )
16 {
17 excelkk.Cells[ 1 , 1 + i] = myTable.Columns[i].ColumnName.ToString();
18 }
19 for ( int i = 0 ; i < myTable.Rows.Count; i ++ )
20 {
21 for ( int j = 0 ; j < myTable.Columns.Count; j ++ )
22 {
23 excelkk.Cells[row, j + 1 ] = myTable.Rows[i][j].ToString();
24 }
25
26 row ++ ;
27 }
28
29
30 // 取得特定單元格的值
31 excelkk.Visible = true ;
32 this .TextBoxChange.Text = excelkk.get_Range( " A2 " , Type.Missing).Text.ToString();
33 // 表的單元格合并
34 Excel.Range range1 = excelkk.get_Range( " A2 " , " D4 " );
35 range1.Merge(Type.Missing);
36
37
38
39
40 // 想表格中插入求和的值
41 Excel.Range range2 = excelkk.get_Range( " B25 " , Type.Missing);
42 range2.Formula = " =SUM(B2:B24) " ;
43 range2.Calculate();
44
45 // 進行宏的循環應用與單元格的刪除和添加,多個單元格默認宏自動操作。
46 Excel.Range range3 = excelkk.get_Range( " B25 " , " E25 " );
47 range2.AutoFill(range3,Excel.XlAutoFillType.xlFillDefault);
48 // 刪除表的指定行數操作
49 Excel.Range range7 = null ;
50 range7 = excelkk.get_Range(excelkk.Cells[ 2 , 2 ], excelkk.Cells[ 4 , 4 ]);
51 range7.Select();
52 range7.EntireRow.Delete(Excel.XlDirection.xlUp);
53
54 // 獲取最大用過的行數
55 Excel.Worksheet wsheet1 = (Excel.Worksheet)excelkk.Worksheets.get_Item( 1 );
56 int n = wsheet1.UsedRange.Cells.Columns.Count;
57 Response.Write(n.ToString() + " <br> " );
58 // MessageBox.Show(n.ToString());
59 n = wsheet1.UsedRange.Cells.Rows.Count;
60 Response.Write(n.ToString() + " <br> " );
61 // MessageBox.Show(n.ToString());
62 // 數據的複製
63 Excel.Range range4 = excelkk.get_Range( " A2 " , " B25 " );
64 Excel.Range range5 = excelkk.get_Range( " E3 " , " F25 " );
65 // range4.get_Offset(1,4).Select();
66 range4.Copy(range5);
67 // 停用警告信息
68 excelkk.DisplayAlerts = false ;
69 GC.Collect();
70
71 }
72
73
74 單個sheet里求和:
75 Excel.Range range2 = excelkk.get_Range( " B25 " , Type.Missing);
76 range2.Formula = " =SUM(B2:B24) " ;
77 range2.Calculate();
78
79 跨sheet求和:
80 Excel.Worksheet wsheet1 = (Excel.Worksheet)excelSql.Worksheets.get_Item( 1 );
81 Excel.Range range3 = wsheet1.get_Range( " A23 " , Type.Missing);
82 range3.Formula = " =Sheet3!B8+Sheet3!B12 " ;
83 range3.Calculate();
84

         虽然我们拥有强大的NPOI,不过我还是写出来,希望对大家理解office有一定的用处。

有错误的地方欢迎大家拍砖,希望交流和共享。

 

在ASP.NET中使用Excel类读取Excel文件数据时,会碰到一些奇怪问题,例如“无法读取”等,一般是由于ASP.NET帐户没有操作Excel的权限等原因造成的。解决方法如下:


    运行dcomcnfg(DCOM Config), 在列表中选择Microsoft Excel应用程序,查看属性,身份验证级别选"无",身份标识选"交互式用户",安全性页面,启动和访问均给everyone。(选择安全性选项,编辑可以启动应用程序的用户和更改应用程序配置的用户,在用户中添加ASP.NEt帐户。然后重新启动计算机)(必须,否则仍然无法使用Excel类)。


    做如上配置以后,即可以使用如下方法把Excel中的数据读取到一个DataSet中:

public static DataSet ReadExcel2DataSet(string filePath)
{

   //新建Excel应用程序对象,用于操作Excel
   Excel.Application app = new Excel.ApplicationClass();

   try
   {  

       //打开Excel文件
       app.Workbooks.Open  (filePath,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
     Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);

    DataSet ds = new DataSet();
    for(int i=1; i<=app.Worksheets.Count; i++)
    {
       Excel.Worksheet worksheet = app.Worksheets[i] as Excel.Worksheet;
       Excel.Range rngUsed = worksheet.UsedRange;

       DataTable dt = new DataTable();
       ds.Tables.Add(dt);
       for(int j=0; j<rngUsed.Columns.Count; j++)
       {
         dt.Columns.Add();
       }
        
       object[,] table = ((Excel.Range)rngUsed.Rows).Value2 as object[,];
       if(table == null)
       {
          continue;
       }

       for(int m=1; m<=table.GetLength(0); m++)
       {
         DataRow dr = dt.NewRow();
         dt.Rows.Add(dr);     
         for(int n=1; n<=dt.Columns.Count; n++)
         {
           dr[n-1] = table.GetValue(m,n);
         }
       }
    }

    app.Workbooks[1].Close(Missing.Value,Missing.Value,Missing.Value);   
    return ds;
   }
   catch
   {   
     throw;   
   }
   finally
   {
     app.Quit();
   }
  }

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gentle_wolf/archive/2008/11/27/3394452.aspx

转载于:https://www.cnblogs.com/ceci/archive/2010/09/23/1833344.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值