asp.net sql数据导入excel word问题

就是在页面点击按钮后,提取数据库里面里面的的一些数据写入到excel里面
有一个好看的样式,不通过gridview这样的控件
求详细的代码,如果可以的话还可以加分,请各位高手指点
贴出来也可,发给我也行
邮箱[email protected]
excel的路径 最好可选

public void ExportToExcel(System.Data.DataTable dt)
{
if (dt == null) return;
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
// lblMsg.Text = "无法创建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 = null;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;

//写入标题
range = worksheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, 5]);
range.MergeCells = true;
range.RowHeight = 20;
range.Font.Bold = true;
range.Font.Size = 10;
range.Font.ColorIndex = 10;//字体颜色
xlApp.ActiveCell.FormulaR1C1 = strSite_Name;

for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
range = (Excel.Range)worksheet.Cells[2, i + 1];
//range.Interior.ColorIndex = 15;//背景颜色
range.Font.Bold = true;//粗体
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//居中
//加边框
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
//range.ColumnWidth = 4.63;//设置列宽
//range.EntireColumn.AutoFit();//自动调整列宽
//r1.EntireRow.AutoFit();//自动调整行高

}
//写入内容
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
range = (Excel.Range)worksheet.Cells[r + 3, i + 1];
range.Font.Size = 9;//字体大小
//加边框
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.EntireColumn.AutoFit();//自动调整列宽
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}
((Excel.Range)worksheet.Cells[2, 1]).ColumnWidth = 25;
((Excel.Range)worksheet.Cells[2, 2]).ColumnWidth = 25;
((Excel.Range)worksheet.Cells[2, 3]).ColumnWidth = 20;
((Excel.Range)worksheet.Cells[2, 4]).ColumnWidth = 20;
((Excel.Range)worksheet.Cells[2, 5]).ColumnWidth = 60;

range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
}

try
{
workbook.Saved = true;
workbook.SaveCopyAs("C:\\Documents and Settings\\Administrator\\桌面\\Log.xls");
MessageBox.Show("Export Successful!");
}
catch (Exception ex)
{
}

workbooks.Close();
if (xlApp != null)
{
xlApp.Workbooks.Close();

xlApp.Quit();

int generation = System.GC.GetGeneration(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

xlApp = null;
System.GC.Collect(generation);
}
GC.Collect();//强行销毁

#region 强行杀死最近打开的Excel进程
System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
System.DateTime startTime = new DateTime();
int m, killId = 0;
for (m = 0; m < excelProc.Length; m++)
{
if (startTime < excelProc[m].StartTime)
{
startTime = excelProc[m].StartTime;
killId = m;
}
}
if (excelProc[killId].HasExited == false)
{
excelProc[killId].Kill();
}
#endregion

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-07-20
把Excel看成一个数据库,和SQl数据互相倒入数据。select可以把Excel中的数据取出,insert插入到SQL中,如果反之也相同.
一、定义文档类型、字符编码
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc || .xls || .txt ||.htm
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentType指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
二、定义一个输入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
三、将目标数据绑定到输入流输出
this.RenderControl(oHtmlTextWriter);
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
Response.Write(oStringWriter.ToString());
Response.End();

这个没有考虑要输出的格式,我做过一个连续导入多张表的,那个格式要注意.

鄙人寡闻,已倾力相助
第2个回答  2010-08-05
既然你知道gridview可以导出成Excel,那就好办。
把要生成的Excel或Word在GridView里生成好,然后隐藏GridView控件,其他操作一样就行了。

不推荐使用VBA,那样需要服务器上安装Office,而且效率不高,而且生成的office文件是保存在服务器上的,可选路径的说法基本没有意义。
第3个回答  2010-07-20
虽然,sql server中的DTS也能将数据倒入Excel,但不如使用程序灵活,
本程序主要代码在按钮函数内。可适应于报表开发的读取数据部分:)
我删除了原程序的很多垃圾代码,只留主要起作用的代码

//加入名称空间
using System.Data;
using System.Data.SqlClient;

//定义方法GetData(),返回一个数据表
private System.Data.DataTable GetData()
{
SqlConnection conn= new SqlConnection(@"Server=PXGD2;Initial Catalog=pingxiang;Uid=sa;Pwd=;");
SqlDataAdapter adapter= new SqlDataAdapter("select username 用户名,catalyst_port 占用端口,home_address 住宅地址,ip_address

ip地址,phone 电话,addtime 开通日期 from userinfo where catalyst_port=1 or catalyst_port='' order by ip_address desc",conn);

DataSet ds= new DataSet();
try
{
adapter.Fill(ds,"Customer");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
return ds.Tables[0];
}

//按钮
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application excel= new Excel.Application();
int rowIndex=1;
int colIndex=0;

excel.Application.Workbooks.Add(true);

DataTable table=GetData();

//将所得到的表的列名,赋值给单元格
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();
}
}
//不可见,即后台处理
excel.Visible=true;
}
第4个回答  2010-07-20
dim rs,sql,filename,fso,myfile,x

Set fso= server.CreateObject("scripting.filesystemobject")
filename=Server.MapPath("rzyh.xls")
if fso.FileExists(filename) then
fso.DeleteFile(filename)
end if
'--创建EXCEL文件
set myfile=fso.CreateTextFile(filename,true)

if rs.EOF and rs.BOF then
response.write("<script>alert('无数据导出!!');location.href='wenjian.asp';</script>")
response.end
else
dim strLine,responsestr
strLine=""
'--将表的列名先写入EXCEL
For each x in rs.fields
strLine = strLine & x.name & chr(9)
Next
myfile.writeline strLine
Do while Not rs.EOF
strLine=""
for each x in rs.Fields
strLine = strLine & x.value & chr(9)
next
'--将表的数据写入EXCEL
myfile.writeline strLine
rs.MoveNext
loop
response.write("<script>alert('已经导出!!');</script>")
response.write("<script>setTimeout('window.opener=null;history.back();',2800);location='rzyh.xls';</script>")
end if
rs.Close
set rs = nothing
Response.ContentType="application/x-msdownload"

里面的RS 是一个COM对象,是用ADO组件打开数据库时用的“记录集”对象。赋值到rs上了。
你可以把NET里面的DataSet改下 试试
希望对你有帮助,路径是随便保存的,
是读取列表的值 全部导入EXCEL里面
第5个回答  2010-07-20
我有vs2008的详细的代码需要吗 HI我啊 qq:582044384(注明百度知道)
相似回答
大家正在搜