C#导入excel的问题
WebForm中,要把sqlServer的信息导入到excel中,应该怎样实现?
------解决方案--------------------protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
//Response.Charset = "GB2312 ";
Response.AppendHeader( "Content-Disposition ", "attachment;filename=Report.xls ");
//Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel ";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.divResult.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{ }
------解决方案--------------------ddd
------解决方案--------------------我这种方法是通过ADO.net读取出DataSet 后输出的
SqlConnection conn=DB.createCon();;
SqlDataAdapter da=new SqlDataAdapter( "select * from product ",conn);
DataSet ds=new DataSet();
da.Fill(ds, "table1 ");
DataTable dt=ds.Tables[ "table1 "];
StringWriter sw=new StringWriter();
//EXCEL显示的列头名
sw.WriteLine( "自动编号\t姓名\tSid ");
//读取数据
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr[ "pID "]+ "\t "+dr[ "pName "]+ "\t "+dr[ "pSexID "]);
}
sw.Close();
Response.AddHeader( "Content-Disposition ", "attachment; filename=test.xls ");
Response.ContentType = "application/ms-excel ";
Response.ContentEncoding=System.Text.Encoding.GetEncoding( "GB2312 ");
//输出
Response.Write(sw);
Response.End();
------解决方案--------------------public void Createxcal(DataSet ds)//服务器端启动
{
Excel.Application excel = new Excel.Application();
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);
excel.Visible = true;
DataTable table = ds.Tables[0];
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
}
public void CreateBoweser(DataSet ds)//客户端启动
{
HttpContext curContext = HttpContext.Current;
StringWriter strwriter = null;
HtmlTextWriter htmlwriter = null;
DataGrid dg = new DataGrid();
if (ds != null)
{
curContext.Response.ContentType = "application/vnd.ms-excel ";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = " ";
strwriter = new StringWriter();