数据导出到Excel(或Word)源代码大全
在日常工作中,大家都习惯Office作为办公软件,因此,在开发软件的时,常常会有把数据导出到Excel等Office软件的需求。在此,收集一些常用的导出文件的源程序,希望给大家带来方便。(不断更新)
一、DataSet数据集内数据转化为Excel
-
-
-
- // 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
- public void DataSetToExcel(DataSet ds,string FileName)
- {
- try
- {
-
-
-
- HttpResponse resp;
- resp=HttpContext.Current.Response;
- resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
- resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
- resp.ContentType="application/ms-excel";
- //变量定义
- string colHeaders=null;
- string Is_item=null;
- //显示格式定义
-
- //文件流操作定义
- //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
- //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
- StringWriter sfw=new StringWriter();
- //定义表对象与行对象,同时用DataSet对其值进行初始化
- System.Data.DataTable dt=ds.Tables[0];
- DaTarow[] myRow=dt.Select();
- int i=0;
- int cl=dt.Columns.Count;
- //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
- for(i=0;i<cl;i++)
- {
-
-
- //else
- colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
- }
- sfw.WriteLine(colHeaders);
- //sw.WriteLine(colHeaders);
- //逐行处理数据
- foreach(DaTarow row in myRow)
- {
- //当前数据写入
- {
-
-
- Is_item+=row[i].ToString()+"/t";
- }
- sfw.WriteLine(Is_item);
- //sw.WriteLine(Is_item);
- Is_item= resp.Write(sfw);
- //resp.Clear();
- resp.End();
- }
- catch(Exception e)
- {
- throw e;
- }
二、DataSet数据集内数据转化为Excel文件(2)
/// <summary>
/// ExportFiles 的摘要说明。
/// 作用:把DataSet数据集内数据转化为Excel文件
/// 描述:导出Excel文件
/// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
/// </summary>
class ExportFiles
private string filePath = "";
public ExportFiles(string excel_path)
{
filePath = excel_path;
}
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
bool ExportToExcel(System.Data.DataSet ds, string ReportName)
if (ds.Tables[0].Rows.Count == 0)
{
MessageBox.Show("数据集为空");
}
Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
Workbook xlbook = xlapp.Workbooks.Add(true);
Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
range.MergeCells = true;
xlapp.ActiveCell.FormulaR1C1 = ReportName;
xlapp.ActiveCell.Font.Size = 20;
xlapp.ActiveCell.Font.Bold = true;
xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
int colIndex = 0;
int RowIndex = 2;
//开始写入每列的标题
foreach (DataColumn dc in ds.Tables[0].Columns)
colIndex++;
xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
}
//开始写入内容
int RowCount = ds.Tables[0].Rows.Count;
for (int i = 0; i < RowCount; i++)
{
RowIndex++;
int ColCount = ds.Tables[0].Columns.Count;
for (colIndex = 1; colIndex <= ColCount; colIndex++)
{
xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];
xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;
}
xlbook.Saved = xlbook.SavecopyAs(filePath);
xlapp.Quit();
GC.Collect();
return }
bool ExportToExcelOF(System.Data.DataSet ds,153); font-weight:bold; background-color:inherit">string ReportName)
{
if (ds.Tables[0].Rows.Count == 0)
MessageBox.Show("数据集为空");
string FileName = filePath;
//System.Data.DataTable dt = new System.Data.DataTable();
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "";
objFileStream = new FileStream(FileName, FileMode.OpenorCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
strLine = ReportName;
objStreamWriter.WriteLine(strLine);
strLine = "";
int i = 0; i < ds.Tables[0].Columns.Count; i++)
strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + " " + Convert.tochar(9);
objStreamWriter.WriteLine(strLine);
strLine = "";
int i = 0; i < ds.Tables[0].Rows.Count; i++)
strLine = strLine + (i + 1) + Convert.tochar(9);
int j = 1; j < ds.Tables[0].Columns.Count; j++)
{
strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.tochar(9);
objStreamWriter.WriteLine(strLine);
strLine = "";
objStreamWriter.Close();
objFileStream.Close();
//Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
//Workbook xlbook = xlapp.Workbooks.Add(true);
//Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
//Range range = xlsheet.get_Range(xlapp.Cells[1, ds.Tables[0].Columns.Count]);
//range.EntireColumn.AutoFit();
//xlapp.Quit();
}
}
三、生成XML然后转换成Excel方式
参考资源:http://www.codeproject.com/office/Excel_Export.asp?df=100&forumid=329437&fr=51 (源程序)
优点:
a. 服务端不用安装Excel程序。
b. 支持一定的Excel文件格式设置,比如字体大小、颜色、合并单元格等。
缺点:
a. 与Excel 2000不兼容:由于Excel 2000不支持XML,所以以这种方法生成的Excel文件可能在Excel2000中不兼容(毕竟目前还有不少用户的电脑装的是Excel 2000)。
b. 可能不支持Excel文件页边距的设置;不支持Excel文件横向、纵向的设置;不支持Excel模板;
c. 编程工作量比较大;
d. 生成的文件本质上是XML文件,需要“另存为xls”才能变成真正的Excel文件。
e. 性能是好是坏还不清楚,目前还没真正在项目中用过。希望有用过此方案的朋友能介绍一下这个方案的性能。
四、导出GridView到Excel
//导出GridView到Excel中的关键之处
//用法: ToExcel(Gvstaff, TextBox1.Text);
static void ToExcel(System.Web.UI.Control ctl,153); font-weight:bold; background-color:inherit">string FileName)
{
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-disposition","attachment;filename="+""+FileName+".xls");
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
必须有下面这句!否则不会通过!
override void VerifyRenderingInServerForm(Control control)
// Confirms that an HtmlForm control is rendered for
}
五、DataTable导出到Excel
using System;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace DongVI
/// 整理:dongVi
class DataTabletoExcel
{
private DataTabletoExcel()
{
}
/// <param name="dt">要导出的DataTable</param>
void ExportToExcel(System.Data.DataTable dt )
if (dt == null) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
// lblMsg.Text = "无法创建Excel对象,可能您的电脑未安装Excel";
MessageBox.Show( "无法创建Excel对象,可能您的电脑未安装Excel" );
return;
}
System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
saveDia.Filter = "Excel|*.xls";
saveDia.Title = "导出为Excel文件";
if(saveDia.ShowDialog()== System.Windows.Forms.DialogResult.OK
&& !string.Empty.Equals(saveDia.FileName))
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range = long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
string fileName = saveDia.FileName;
//写入标题
int i = 0; i < dt.Columns.Count; i++)
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Font.Bold = true;
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.BorderAround(Microsoft.Office.Interop.Excel.XlLinestyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,153); font-weight:bold; background-color:inherit">null);
//range.ColumnWidth = 4.63;//设置列宽
//range.EntireColumn.AutoFit();//自动调整列宽
//r1.EntireRow.AutoFit();//自动调整行高
//写入内容
int r = 0; r < dt.defaultview.Count; r++)
{
worksheet.Cells[r + 2, i + 1] = dt.defaultview[r][i];
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> range.Font.Size = 9;
range.BorderAround(Microsoft.Office.Interop.Excel.XlLinestyle.xlContinuous,248)"> range.EntireColumn.AutoFit();
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
try
workbook.Saved = workbook.SavecopyAs(fileName);
catch (Exception ex)
//lblMsg.Text = "导出文件时出错,文件可能正被打开!/n" + ex.Message;
MessageBox.Show( "导出文件时出错,文件可能正被打开!/n" + ex.Message );
workbooks.Close();
if (xlApp != xlApp.Workbooks.Close();
xlApp.Quit();
int generation = System.GC.GetGeneration(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = 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
MessageBox.Show( "导出成功!" );
}
}
}
六、DataTable导出到excel(2)
StringWriter stringWriter = HtmlTextWriter htmlWriter = new HtmlTextWriter( stringWriter );
DataGrid excel = new DataGrid();
System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle itemStyle = AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.BackColor =System.Drawing.Color.LightGray;
headerStyle.Font.Bold = headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;;
excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
excel.HeaderStyle.MergeWith(headerStyle);
excel.ItemStyle.MergeWith(itemStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = excel.DataSource = dt.defaultview;
excel.DataBind();
excel.RenderControl(htmlWriter);
string filestr = "d://data//"+filePath;
int pos = filestr.LastIndexOf( "//");
string file = filestr.Substring(0,pos);
if( !Directory.Exists( file ) )
Directory.CreateDirectory(file);
}
System.IO.StreamWriter sw = new StreamWriter(filestr);
sw.Write(stringWriter.ToString());
sw.Close();
七、通过sql直接导出到Excel数据库
exec master..xp_cmdshell @# bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout c:/test.xls -c -S"soa" -U"sa" -P"sa" @#
注意:参数的大小写,另外这种方法写入数据的时候没有标题。
关于通过sql读取EXCEL的方法请参见:http://blog.csdn.net/wonsoft/archive/2008/11/16/3312320.aspx
八、用OleDB 把 DataSet 数据导出到 Excel文件里
//dt为数据源(数据表)
//ExcelFileName 为要导出的Excle文件
//ModelFile为模板文件,该文件与数据源中的表一致。否则数据会导出失败。
//ModelFile文件里,需要有一张 与 dt.TableName 一致的表,而且字段也要一致。
//注明:如果不用ModelFile的话,可以用一个空白Excel文件,不过,要去掉下面创建表的注释,让OleDb自己创建一个空白表。
string TabletoExcelFile(DataTable dt,153); font-weight:bold; background-color:inherit">string ExcelFileName,153); font-weight:bold; background-color:inherit">string ModelFile)
File.copy(ModelFile,ExcelFileName);
if(File.Exists(ExcelFileName)==false)
return "系统创建临时文件失败,请与系统管理员联系!";
if(dt == return "DataTable不能为空";
int rows = dt.Rows.Count;
int cols = dt.Columns.Count;
StringBuilder sb;
string connString;
if(rows == 0)
return "没有数据";
sb = new StringBuilder();
connString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ExcelFileName+";Extended Properties=Excel 8.0;";
//生成创建表的脚本
//----sb.Append("DROP TABLE "+dt.TableName);
/*
sb.Append(dt.TableName + " ( ");
for(int i=0;i<cols;i++)
{
if(i < cols - 1)
sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName));
else
sb.Append(string.Format("{0} varchar)",0); background-color:inherit"> }
*/
//return sb.ToString();
OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
//objCmd.CommandText=sb.ToString();
objConn.open();
//objCmd.ExecuteNonQuery();
catch(Exception e)
return "在Excel中创建表失败,错误信息:" + e.Message;
sb.Remove(0,sb.Length);
sb.Append("INSERT INTO ");
sb.Append(dt.TableName + " ( ");
for(int i=0;i<cols;i++)
if(i < cols - 1)
sb.Append(dt.Columns[i].ColumnName + ",");
else
sb.Append(dt.Columns[i].ColumnName + ") values (");
sb.Append("@" + dt.Columns[i].ColumnName + ",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> sb.Append("@" + dt.Columns[i].ColumnName + ")");
//建立插入动作的Command
objCmd.CommandText = sb.ToString();
OleDbParameterCollection param = objCmd.Parameters;
param.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, OleDbType.VarChar));
//遍历DataTable将数据插入新建的Excel文件中
foreach (DaTarow row in dt.Rows)
{
int i=0; i<param.Count; i++)
param[i].Value = row[i];
objCmd.ExecuteNonQuery();
return "数据已成功导入Excel";
}
// Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=754176
九、利用OLEDB,以excel为数据库,把dataset中的数据导入到excel文件中
void
exportToExcelByDataset(string filePath, DataSet ds,XmlNode node)
string sqlstr;
if(fi.Exists)
fi.Delete();
//throw new Exception("文件删除失败");
else
fi.Create();
string mailto:sqlcon=@%22Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended ProPerties=Excel 8.0;";
OleDbConnection olecon = new OleDbConnection(sqlcon);
OleDbCommand olecmd = new OleDbCommand();
olecmd.Connection = olecon;
olecmd.CommandType = CommandType.Text;
olecon.open();
XmlNode nodec=node.SelectSingleNode("./Method/ShowField");
int ii = 0;
sqlstr = "CREATE TABLE sheet1(";
foreach(XmlNode xnode in nodec.ChildNodes )
if(ii == nodec.ChildNodes.Count - 1)
{
if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")
{
sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number)";
}
sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";
}
sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number,";
sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text,";
}
ii++;
}
olecmd.CommandText = sqlstr;
olecmd.ExecuteNonQuery();
int i=0;i<ds.Tables[0].Rows.Count;i++)
{
sqlstr = "INSERT INTO sheet1 VALUES(";
int jj=0;
foreach(XmlNode inode if(jj == nodec.ChildNodes.Count-1)
{
if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
{
sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + ")" ;
}
sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "')" ;
}
{
if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
{
sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + "," ;
}
sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "',248)"> }
jj++;
olecmd.CommandText = sqlstr;
olecmd.ExecuteNonQuery();
}
MessageBox.Show(@"Excel文件:" + filePath + " 导出成功!");
catch(Exception ex)
MessageBox.Show(ex.Message);
finally
olecmd.dispose();
olecon.Close();
olecon.dispose();
}
// 判断对象为空
string isnull(string obj)
if(obj.Length >0)
return obj;
return "null";
}
}
鸣谢:感谢各位作者的无私奉献!世界有你们真精彩。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。