先将数据绑定到一个控件中,例" />
乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > 急!!!在<em>asp</em>.net C#中,如何将<em>数据库</

急!!!在<em>asp</em>.net C#中,如何将<em>数据库</

作者:乔山办公网日期:

返回目录:excel表格制作


首先 你电脑上面必须安装有Excel 然后你在引用Excel 就可以操作代码

先将数据绑定到一个控件中,例如gridview:
放一个按钮,代e79fa5e98193e78988e69d83338码如下:
protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
{
string FileName = "标题 " + DateTime.Now + ".xls";
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.UTF8;//System.Text
//如果设置GB2312会出现乱码
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.AddHeader("content-type", "application / ms - excel");//设置输出文件的类型
//或Response.ContentType = FileType;
//定义一个输出流
StringWriter tw = new StringWriter();//System.IO
HtmlTextWriter hw = new HtmlTextWriter(tw);
gridview1.RenderControl(hw);//gridview绑定
Response.Write(tw.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
//必须写这个;
}
导入excel库。 把数据放到 datagridview中。
Response.Clear();//清除缓冲区流中所有内容的输出
Response.Buffer = true;//获取和设置一个值,该值指出是否缓冲输出,并在完成处理整个响应之后将其发送
Response.Charset = "GB2312";//获取和设置输出流的http字符集;
Response.AppendHeader("Content-Disposition", "attachment;filename = FileName.xls");//将http头添加到输出流
//如果设置成GB2312导出的将是乱码
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件
System.IO.StringWriter oStringWriter = new StringWriter();//实现一e69da5e6ba90e799bee5baa6330个用于将信息写入字符串 TextWriter 该信息存储在基础StringBuilder 中
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);//将标记字符和文本写入到asp.net控件输出流
this.GV_WJ.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();//向客户端发送所有输出流
Response.End();//结束

给你源码自己研究一下,不会来找我

c#导出excel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication3
{
public partial class Form1 : Form
{
private Microsoft.Office.Interop.Excel.Application m_objExcel = null;
private Microsoft.Office.Interop.Excel.Workbooks m_objBooks = null;
private Microsoft.Office.Interop.Excel._Workbook m_objBook = null;
private Microsoft.Office.Interop.Excel.Sheets m_objSheets = null;
private Microsoft.Office.Interop.Excel._Worksheet m_objSheet = null;
private Microsoft.Office.Interop.Excel.Range m_objRange = null;
//private Microsoft.Office.Interop.Excel.Font m_objFont = null;
//private Microsoft.Office.Interop.Excel.QueryTables m_objQryTables = null;
private Microsoft.Office.Interop.Excel._QueryTable m_objQryTable = null;
// Frequenty-used variable for optional arguments.
private object m_objOpt = System.Reflection.Missing.Value;
//DataBase-used variable
private System.Data.SqlClient.SqlConnection sqlConn = null;
private string strConnect = "Data Source='localhost';Password = ;User ID=sa;Initial Catalog=TEST";
private System.Data.SqlClient.SqlCommand sqlCmd = null;

//Sheets variable
private double dbSheetSize = 65535;//the hight limit number in one sheet
private int intSheetTotalSize = 0;//total record can divied sheet number
private double dbTotalSize = 0;//record total number

public Form1()
{
InitializeComponent();
}

private int GetTotalSize()
{
sqlConn = new System.Data.SqlClient.SqlConnection(strConnect);
sqlCmd = new System.Data.SqlClient.SqlCommand("Select Count(*) From PD_WORKBIL_MST", sqlConn);
sqlConn.Open();
dbTotalSize = (int)sqlCmd.ExecuteScalar();
sqlConn.Close();
return (int)Math.Ceiling(dbTotalSize / this.dbSheetSize);
}
private void DeclareExcelApp()
{
m_objExcel = new Microsoft.Office.Interop.Excel.Application();
m_objBooks = (Microsoft.Office.Interop.Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = (Microsoft.Office.Interop.Excel._Workbook)(m_objBooks.Add(m_objOpt));
m_objSheets = (Microsoft.Office.Interop.Excel.Sheets)m_objBook.Worksheets;
intSheetTotalSize = GetTotalSize();
if (intSheetTotalSize <= 3)
{
if (this.dbTotalSize <= this.dbSheetSize)
{
this.ExportDataByQueryTable(1, false);
return;
}
else if (this.dbTotalSize <= this.dbSheetSize * 2)
{
this.ExportDataByQueryTable(1, false);
this.ExportDataByQueryTable(2, true);
return;
}
else
{
this.ExportDataByQueryTable(1, false);
this.ExportDataByQueryTable(2, true);
this.ExportDataByQueryTable(3, true);
return;
}
}
for (int i = 3; i < intSheetTotalSize; i++)
{
m_objSheets.Add(m_objOpt, m_objSheets.get_Item(i), m_objOpt, m_objOpt);
}
ExportDataByQueryTable(1, false);
for (int i = 2; i <= m_objSheets.Count; i++)
{
ExportDataByQueryTable(i,true);
}
}
private void SaveExcelApp()
{
string excelFileName = string.Empty;
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "*.xls|*.*";
if (sf.ShowDialog() == DialogResult.OK)
{
excelFileName = sf.FileName;
}
else
{
return;
}
m_objBook.SaveAs(excelFileName, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
private void ExportDataByQueryTable(int intSheetNumber,bool blIsMoreThan)
{
string strQuery = string.Empty;
if (blIsMoreThan)
{
strQuery = "Select Top " +
this.dbSheetSize + " * From PD_WORKBIL_MST Where Not CMPID In (Select Top " +
dbSheetSize * (intSheetNumber-1) + " CMPID From PD_WORKBIL_MST)";
}
else
{
strQuery = "Select Top " +this.dbSheetSize + " * From PD_WORKBIL_MST ";

}
m_objSheet = (Microsoft.Office.Interop.Excel._Worksheet)(m_objSheets.get_Item(intSheetNumber));
m_objSheet.get_Range("A1", m_objOpt).set_Value(m_objOpt, "中文测试一");
m_objSheet.get_Range("B1", m_objOpt).set_Value(m_objOpt, "中文测试二");
m_objSheet.get_Range("C1", m_objOpt).set_Value(m_objOpt, "中文测试三");
m_objSheet.get_Range("D1", m_objOpt).set_Value(m_objOpt, "中文测试四");
m_objSheet.get_Range("E1", m_objOpt).set_Value(m_objOpt, "中文测试五");
m_objRange = m_objSheet.get_Range("A2", m_objOpt);
m_objQryTable = m_objSheet.QueryTables.Add("OLEDB;Provider=SQLOLEDB.1;" + strConnect, m_objRange, strQuery);
m_objQryTable.RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertEntireRows;
m_objQryTable.FieldNames = false;
m_objQryTable.Refresh(false);
}
private void button1_Click(object sender, EventArgs e)
{
DeclareExcelApp();
SaveExcelApp();
}
}
}

第二个人的:

以前做过这个东西,我把以前的学习笔记发给楼主,希望对你有点帮助.这些解决方案都不是最完美的.完美的可以用钱去买.有第三方控件卖.

例一:很简单,不也需要在服务器和客户端配置什么,但是没有封装.

string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringBOB"].ToString();
SqlConnection cn = new SqlConnection(strcon);
SqlDataAdapter da = new SqlDataAdapter("SELECT ftitle,senddate,sender,RecCom FROM [Bulletin] ORDER BY [senddate]", cn);
DataSet ds = new DataSet();
da.Fill(ds, "Bulletin");
DataTable dt = ds.Tables["Bulletin"];
System.IO.StringWriter sw = new System.IO.StringWriter();
sw.WriteLine("标题\t发布时间\t发布人\t发送范围");
foreach (DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ftitle"] + "\t " + dr["senddate"] + "\t" + dr["sender"] + "\t" + dr["RecCom"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment;filename=SmartOA.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();

例二:需要在服务器上进行配置,但实现的功能强大.
具体的配置过程如下:

1:在服务器上安装Excel.

2:文件工作目录everyone用户必须拥有修改的权限.

3:在web.config文件中加入:

<system.web>
.......//其它配置信息
<identity impersonate="true"/>
.......//其它配置信息
</system.web>

using System;
using System.Data;
using System.Data.SqlClient;
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.Reflection;
using Microsoft.Office.Core;

/// <summary>
/// OutPutExcel 的摘要说明
/// </summary>
public class OutPutExcel
{
public OutPutExcel()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
//设置文件的名称属性.
private string _xfileName;
public string xFileName
{
get { return _xfileName; }
set { _xfileName = value; }
}

public void OutputExcel(DataView dv, string titleStr,string sheetName)
{
GC.Collect();
Excel.Application excel;// = new Application();
int rowIndex = 4;
int colIndex = 0;

Excel._Workbook xBk;
Excel._Worksheet xSt;

excel = new Excel.ApplicationClass();

xBk = excel.Workbooks.Add(true);

xSt = (Excel._Worksheet)xBk.ActiveSheet;
xSt.Name = sheetName;
//
//取得表格中各列的标题
//
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 = Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
}

//
//取得表格中的数据
//
foreach (DataRowView row in dv)
{
rowIndex++;
colIndex = 0;
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 = Excel.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 = Excel.XlVAlign.xlVAlignCenter;//设置字符e799bee5baa6e997aee7ad94e78988e69d83331型的字段格式为居中对齐
}
else
{
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加载一个合计行
//
int rowSum = rowIndex;
//int colSum = 2;
//excel.Cells[rowSum, 2] = "合计";
//xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.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] = titleStr;
//
//设置整个报表的标题格式
//
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, 2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, 2]).Font.Size = 12;
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Select();
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Columns.AutoFit();
//
//设置整个报表的标题为跨列居中
//
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, colIndex]).Select();
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;
//
//设置报表表格里的字体大小.
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Font.Size = 9;
//
//绘制边框
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, 1]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlMedium;//设置左边线加粗
xSt.get_Range(excel.Cells[4, 1], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlMedium;//设置上边线加粗
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlMedium;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum, 1], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlMedium;//设置下边线加粗
//
//显示效果
//
excel.Visible = false;

//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(HttpContext.Current.Server.MapPath(".") + "\\" + xFileName+ ".xls");

dv.Dispose();
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 = HttpContext.Current.Server.MapPath(xFileName + ".xls");

System.IO.FileInfo file = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

// 指定返回的是一个不能被客户端读取的流,必须被下载
HttpContext.Current.Response.ContentType = "application/ms-excel";

// 把文件流发送到客户端
HttpContext.Current.Response.WriteFile(file.FullName);
// 停止页面的执行

HttpContext.Current.Response.End();
}

}
调用举例:

protected void btnOutPut_Click(object sender, EventArgs e)
{
string ParentCode = string.Empty;
string projectunitcode = string.Empty;
//string MaterailCode = string.Empty ;
if (Request.QueryString["ParentCode"] != null)
{
if (Request.QueryString["ParentCode"].ToString() != string.Empty)
{
ParentCode = Request.QueryString["ParentCode"].ToString();
}
}
if (Request.QueryString["projectunitcode"] != null)
{
if (Request.QueryString["projectunitcode"].ToString() != string.Empty)
{
projectunitcode = Request.QueryString["projectunitcode"].ToString();

}
}
CpcecDB cpcecdb = new CpcecDB();
DataSet ds = cpcecdb.getCodeMaterialInfoss(ParentCode, projectunitcode);
DataTable dt = ds.Tables[0];
dt.Columns["MaterailCode"].ColumnName = "设备编号";
dt.Columns["MaterialName"].ColumnName = "设备名称";
dt.Columns["ManufacturerCode"].ColumnName = "生产厂编码";
dt.Columns["ManufacturerName"].ColumnName = "生产厂名称";
dt.Columns["ContractualDate"].ColumnName = "合同交货日期";
dt.Columns["AdjustDate"].ColumnName = "调整交货日期";
dt.Columns["factDate"].ColumnName = "实际完成日期";
dt.Columns["DeviceStatus"].ColumnName = "设备状态";
dt.Columns["Complete"].ColumnName = "进度情况";
dt.Columns["Quality"].ColumnName = "质量状况";
OutPutExcel outputexcel = new OutPutExcel();
outputexcel.xFileName = "huangrun124";
outputexcel.OutputExcel(dt.DefaultView, "报表","123456789");

}

第三个人的:

前台代码

HTML code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http:///1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:Button ID="btToExcel" runat="server" Text="导出Excel" OnClick="btToExcel_Click" /> </div>
</form>
</body>
</html>

后台代码

C# code
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;
public partial class _Default : System.Web.UI.Page
{
db mydb = new db();
protected void Page_Load(object sender, EventArgs e)
{
getData();
}
public void getData()
{
GridView1.DataSource = mydb.getData();
GridView1.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{

}

protected void btToExcel_Click(object sender, EventArgs e)
{
db.ExportExcel(GridView1);

}
}

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for db
/// </summary>
public class db
{
public string strCn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
public db()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getData()
{
DataTable dt = new DataTable();
SqlDataAdapter sqlAda = new SqlDataAdapter("select id ,name from tb4 ", strCn);
sqlAda.Fill(dt);
return dt;
}
/// <summary>
/// 导出成为Excel
/// </summary>
/// <param name="exportTargetGridView">目标GridView</param>
public static void ExportExcel(GridView exportTargetGridView)
{
HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.Charset = "GB2312";

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;

HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.doc");

HttpContext.Current.Response.ContentType = "application/word";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

exportTargetGridView.RenderControl(htw);

HttpContext.Current.Response.Write(sw.ToString());

HttpContext.Current.Response.End();
}
}

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网