有两种方法对gridview进行Excel 输出,一种是gridview 自带的,不用对owc写任何操作,一种是针对microsoft office 的 owc 进行编程。
下面先给出自带的实力,而且这种方法可以实现对gridview完全的打印,也就是说gridview 什么样(颜色,样式)就能打出什么样。
SaveExcel command and close view command;#region SaveExcel command and close view command;
protected void cmdSaveExcel_Click(object sender, EventArgs e)
{
//当前视图保存到Excel
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
string strHtml = oStringWriter.ToString().Trim().Replace("<div>","").Replace("</div>","");
//strHtml = strHtml.Replace("<Table>","").Replace("</Table>","");
string strDate = ddlYear.SelectedItem.Text + ddlMonth.SelectedItem.Text + ddlDay.SelectedItem.Text;
string ExcelFileName = strDate + TreeView1.SelectedNode.Text.Trim() + ".xls";
string FilePhysicialPathName = Request.PhysicalApplicationPath + "/sharereport";
//生成的Excel文件名
string objectExcelFileName = Path.Combine(FilePhysicialPathName, ExcelFileName);
if (File.Exists(objectExcelFileName))
{
File.Delete(objectExcelFileName);
}
strHtml = Server.HtmlDecode(strHtml.Replace(" ", ""));
FileStream fs = new FileStream(objectExcelFileName, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
bw.Write(strHtml);
bw.Flush();
bw.Close();
fs.Close();
Page.RegisterClientScriptBlock("ExcelAlert", "<script>alert('保存成功,请在首页考核报表中查看。');</script>");
}
第二种方法就是打印绑定gridview的table,在这里为了节省,我就直接把打印n个表的类写在这了,道理是一样的。
注意:其中的表都要有表名,和列的头名。
using
System;
using
System.Data;
using
System.Configuration;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
using
System.IO;
using
Excel
=
Microsoft.Office.Interop.Excel;
/**/
/// <summary>
/// SavaExcelToServer 的摘要说明
/// </summary>
public
class
SavaExcelToServer
{
private string m_strDirectory;//Excel文件夹
private string m_strFileName;//Excel文件名
private object[] m_ColumnHead;//表列头对象
private DataTable[] m_dataTable;//导入Excel的表
/**//// <summary>
/// 构造函数
/// </summary>
/// <param name="strDirectory">存Excel的文件夹路径</param>
/// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param>
/// <param name="strColName">列头名数组</param>
public SavaExcelToServer(string strDirectory, string strFileName, DataTable[] dataTable)
{
m_strDirectory = strDirectory;
m_strFileName = strFileName;
m_dataTable = dataTable;
if (!System.IO.Directory.Exists(m_strDirectory))
{
Directory.CreateDirectory(m_strDirectory);
}
if (File.Exists(Path.Combine(m_strDirectory, m_strFileName)))
{
File.Delete(m_strDirectory + "\\" + m_strFileName);
}
}
/**//// <summary>
/// 保存Excel
/// </summary>
public bool SaveExcel()
{
int nCount = 0; //所有表列的记数
int nRowCount = 0; //行数量
int m_ColCount = 0; //列数量
int nSeries = 0; //数组维数
string[] strColName;//表头名数组
object objValue = System.Type.Missing;
object A1;//Excel的列头对象
object H1;//Excel的列头对象
object A2;//Excel的行对象
object H2;//Excel的行对象
Excel.Application EApp;
nSeries = m_dataTable.Length;
for (int i = 0; i < nSeries; i++)
{
m_ColCount += m_dataTable[i].Columns.Count;
}
m_ColumnHead = new object[m_ColCount];
strColName = new string[m_ColCount];
nRowCount = m_dataTable[0].Rows.Count;
for (int j = 0; j < nSeries; j++)
{
for (int k = 0; k < m_dataTable[j].Columns.Count; k++)
{
try { strColName[nCount] = m_dataTable[j].Columns[k].Caption; }
catch { strColName[nCount] = string.Empty; }
nCount++;
}
}
EApp = new Excel.ApplicationClass();
if (EApp == null)
{
Console.WriteLine("不能打开Excel。");
return false;
}
else
{
Excel.Workbooks xlWookBooks = EApp.Workbooks;
Excel.Workbook xlWorkBook = xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
//对象变量初始化
A1 = xlWorkSheet.Cells[1, 1];
H1 = xlWorkSheet.Cells[1, m_ColCount];
A2 = xlWorkSheet.Cells[2, 1];
H2 = xlWorkSheet.Cells[2, m_ColCount];
Excel.Range Range = xlWorkSheet.get_Range(A1, H1);
Range.Columns.HorizontalAlignment = 3;//value 水平居中
//设置Excle的表头
for (int k = 0; k < m_ColCount; k++)
{
try { m_ColumnHead[k] = (object)strColName[k]; }
catch { m_ColumnHead[k] = (object)string.Empty; }
}
Range.Value2 = m_ColumnHead;
//向Excel中写入数据
Range = xlWorkSheet.get_Range(A2, H2);
object[,] ColumnData = new object[nRowCount, m_ColCount];
for (int n = 0; n < nRowCount; n++)
{
int nCountTemp = 0;
for (int i = 0; i < nSeries; i++)
{
for (int j = 0; j < m_dataTable[i].Columns.Count; j++)
{
try { ColumnData[n, nCountTemp] = m_dataTable[i].Rows[n][j]; }
catch { ColumnData[n, nCountTemp] = string.Empty; }
nCountTemp++;
}
}
}
Range = Range.get_Resize(nRowCount, m_ColCount);
Range.Value2 = ColumnData;
//设置Excel的属性
Range.Interior.ColorIndex = 0; //设置其Excel的背景颜色
Range.Columns.HorizontalAlignment = 3; //value 水平居中
Range.Cells.EntireColumn.AutoFit();//.ColumnWidth = 20; //Excel的表格宽度
//保存Excel文件
EApp.Visible = false;
EApp.UserControl = false;
EApp.DisplayAlerts = false;
xlWorkBook.Saved = true;
//EApp.ActiveWorkbook.SaveCopyAs(a);
xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName);
//释放资源
xlWorkBook.Close(false, Type.Missing, Type.Missing);
EApp.Quit();
return true;
}
}
}