print gridview to excel and print several tables to excel(one sheet)

本文介绍两种将ASP.NET中的GridView导出为Excel的方法。第一种利用GridView自带的功能实现完整样式的导出;第二种通过Microsoft Office Web Components (OWC)编程方式导出多个表。这两种方法均可实现在服务器端保存Excel文件。
            有两种方法对gridview进行Excel 输出,一种是gridview 自带的,不用对owc写任何操作,一种是针对microsoft office 的 owc 进行编程。
      
            下面先给出自带的实力,而且这种方法可以实现对gridview完全的打印,也就是说gridview 什么样(颜色,样式)就能打出什么样。

            
ContractedBlock.gifExpandedBlockStart.gifSaveExcel command and close view command;#region SaveExcel command and close view command;
InBlock.gif    protected void cmdSaveExcel_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        //当前视图保存到Excel
InBlock.gif        Response.Clear();
InBlock.gif        Response.Buffer = true;
InBlock.gif        Response.Charset = "utf-8";
InBlock.gif        Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
InBlock.gif        // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
InBlock.gif        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
InBlock.gif
InBlock.gif        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
InBlock.gif        this.EnableViewState = false; 
InBlock.gif
InBlock.gif        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
InBlock.gif        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
InBlock.gif
InBlock.gif        GridView1.RenderControl(oHtmlTextWriter);
InBlock.gif        string strHtml = oStringWriter.ToString().Trim().Replace("<div>","").Replace("</div>","");
InBlock.gif        //strHtml = strHtml.Replace("<Table>","").Replace("</Table>","");
InBlock.gif        string strDate = ddlYear.SelectedItem.Text + ddlMonth.SelectedItem.Text + ddlDay.SelectedItem.Text;
InBlock.gif        string ExcelFileName = strDate + TreeView1.SelectedNode.Text.Trim() + ".xls";
InBlock.gif        string FilePhysicialPathName = Request.PhysicalApplicationPath + "/sharereport";
InBlock.gif        //生成的Excel文件名
InBlock.gif        string objectExcelFileName = Path.Combine(FilePhysicialPathName, ExcelFileName);
InBlock.gif        if (File.Exists(objectExcelFileName))
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            File.Delete(objectExcelFileName);
ExpandedSubBlockEnd.gif        }
InBlock.gif        strHtml = Server.HtmlDecode(strHtml.Replace("&nbsp;", ""));
InBlock.gif        FileStream fs = new FileStream(objectExcelFileName, FileMode.Create, FileAccess.Write);
InBlock.gif        BinaryWriter bw = new BinaryWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
InBlock.gif        bw.Write(strHtml);
InBlock.gif        bw.Flush();
InBlock.gif        bw.Close();
InBlock.gif        fs.Close();
InBlock.gif        Page.RegisterClientScriptBlock("ExcelAlert", "<script>alert('保存成功,请在首页考核报表中查看。');</script>");
ExpandedSubBlockEnd.gif    }


            第二种方法就是打印绑定gridview的table,在这里为了节省,我就直接把打印n个表的类写在这了,道理是一样的。注意:其中的表都要有表名,和列的头名。

None.gifusing System;
None.gif
using System.Data;
None.gif
using System.Configuration;
None.gif
using System.Web;
None.gif
using System.Web.Security;
None.gif
using System.Web.UI;
None.gif
using System.Web.UI.WebControls;
None.gif
using System.Web.UI.WebControls.WebParts;
None.gif
using System.Web.UI.HtmlControls;
None.gif
using System.IO;
None.gif
using Excel = Microsoft.Office.Interop.Excel;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**//// <summary>
InBlock.gif
/// SavaExcelToServer 的摘要说明
ExpandedBlockEnd.gif
/// </summary>

None.gifpublic class SavaExcelToServer
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private string m_strDirectory;//Excel文件夹
InBlock.gif
    private string m_strFileName;//Excel文件名
InBlock.gif
    private object[] m_ColumnHead;//表列头对象
InBlock.gif
    private DataTable[] m_dataTable;//导入Excel的表
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 构造函数
InBlock.gif    
/// </summary>
InBlock.gif    
/// <param name="strDirectory">存Excel的文件夹路径</param>
InBlock.gif    
/// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param>
ExpandedSubBlockEnd.gif    
/// <param name="strColName">列头名数组</param>

InBlock.gif    public SavaExcelToServer(string strDirectory, string strFileName, DataTable[] dataTable)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        m_strDirectory 
= strDirectory;
InBlock.gif        m_strFileName 
= strFileName;
InBlock.gif        m_dataTable 
= dataTable;
InBlock.gif        
InBlock.gif        
if (!System.IO.Directory.Exists(m_strDirectory))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Directory.CreateDirectory(m_strDirectory);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
if (File.Exists(Path.Combine(m_strDirectory, m_strFileName)))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            File.Delete(m_strDirectory 
+ "\\" + m_strFileName);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 保存Excel
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public bool SaveExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
int nCount = 0;     //所有表列的记数 
InBlock.gif
        int nRowCount = 0;  //行数量
InBlock.gif
        int m_ColCount = 0//列数量
InBlock.gif
        int nSeries = 0;    //数组维数
InBlock.gif
        string[] strColName;//表头名数组
InBlock.gif

InBlock.gif        
object objValue = System.Type.Missing;
InBlock.gif        
object A1;//Excel的列头对象
InBlock.gif
        object H1;//Excel的列头对象
InBlock.gif
        object A2;//Excel的行对象
InBlock.gif
        object H2;//Excel的行对象
InBlock.gif
        Excel.Application EApp;
InBlock.gif
InBlock.gif        nSeries 
= m_dataTable.Length;
InBlock.gif        
for (int i = 0; i < nSeries; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            m_ColCount 
+= m_dataTable[i].Columns.Count;
ExpandedSubBlockEnd.gif        }

InBlock.gif        m_ColumnHead 
= new object[m_ColCount];
InBlock.gif        strColName 
= new string[m_ColCount];
InBlock.gif        nRowCount 
= m_dataTable[0].Rows.Count;
InBlock.gif
InBlock.gif        
for (int j = 0; j < nSeries; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
for (int k = 0; k < m_dataTable[j].Columns.Count; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
try dot.gif{ strColName[nCount] = m_dataTable[j].Columns[k].Caption; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
catch dot.gif{ strColName[nCount] = string.Empty; }
InBlock.gif                    nCount
++;
InBlock.gif                
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        EApp 
= new Excel.ApplicationClass();
InBlock.gif
InBlock.gif        
if (EApp == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"不能打开Excel。");
InBlock.gif            
return false;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Excel.Workbooks xlWookBooks 
= EApp.Workbooks;
InBlock.gif            Excel.Workbook xlWorkBook 
= xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls     
InBlock.gif
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
InBlock.gif
InBlock.gif            
//对象变量初始化
InBlock.gif
            A1 = xlWorkSheet.Cells[11];
InBlock.gif            H1 
= xlWorkSheet.Cells[1, m_ColCount];
InBlock.gif            A2 
= xlWorkSheet.Cells[21];
InBlock.gif            H2 
= xlWorkSheet.Cells[2, m_ColCount];
InBlock.gif
InBlock.gif            Excel.Range Range 
= xlWorkSheet.get_Range(A1, H1);
InBlock.gif            Range.Columns.HorizontalAlignment 
= 3;//value 水平居中
InBlock.gif
InBlock.gif            
//设置Excle的表头
InBlock.gif

InBlock.gif            
for (int k = 0; k < m_ColCount; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif                
try dot.gif{ m_ColumnHead[k] = (object)strColName[k]; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{ m_ColumnHead[k] = (object)string.Empty; }
ExpandedSubBlockEnd.gif            }

InBlock.gif            Range.Value2 
= m_ColumnHead;
InBlock.gif
InBlock.gif            
//向Excel中写入数据
InBlock.gif
            Range = xlWorkSheet.get_Range(A2, H2);
InBlock.gif            
object[,] ColumnData = new object[nRowCount, m_ColCount];
InBlock.gif
InBlock.gif            
for (int n = 0; n < nRowCount; n++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int nCountTemp = 0;
InBlock.gif                
for (int i = 0; i < nSeries; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
for (int j = 0; j < m_dataTable[i].Columns.Count; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        

ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
try dot.gif{ ColumnData[n, nCountTemp] = m_dataTable[i].Rows[n][j]; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
catch dot.gif{ ColumnData[n, nCountTemp] = string.Empty; }
InBlock.gif                            nCountTemp
++;
ExpandedSubBlockEnd.gif                        

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            Range 
= Range.get_Resize(nRowCount, m_ColCount);
InBlock.gif            Range.Value2 
= ColumnData;
InBlock.gif            
//设置Excel的属性
InBlock.gif
            Range.Interior.ColorIndex = 0//设置其Excel的背景颜色
InBlock.gif
            Range.Columns.HorizontalAlignment = 3//value 水平居中
InBlock.gif
            Range.Cells.EntireColumn.AutoFit();//.ColumnWidth = 20; //Excel的表格宽度
InBlock.gif
InBlock.gif            
//保存Excel文件
InBlock.gif
            EApp.Visible = false;
InBlock.gif            EApp.UserControl 
= false;
InBlock.gif            EApp.DisplayAlerts 
= false;
InBlock.gif            xlWorkBook.Saved 
= true;
InBlock.gif            
//EApp.ActiveWorkbook.SaveCopyAs(a);
InBlock.gif
            xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName);
InBlock.gif            
InBlock.gif            
//释放资源
InBlock.gif
            xlWorkBook.Close(false, Type.Missing, Type.Missing);
InBlock.gif            EApp.Quit();
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif




转载于:https://www.cnblogs.com/sw22225458/archive/2007/04/26/728696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值