下载

//下载txt

private static void ExportTXT(DataTable tb, string fileName)
{
HttpContext.Current.Response.Clear();//删除缓冲区,必须在启用缓存区(Response.Buffer = true)状态下才能使用,不然报错
string FileName = fileName + ".txt";
HttpContext.Current.Response.Buffer = true; //开启缓冲
HttpContext.Current.Response.Charset = "UTF-8";//输出文件的编码格式,"GB2312"表示简体中文,通用"UTF-8"
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//System.Text.Encoding.UTF7可以兼容邮件下载
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());//固定格式的写法
HttpContext.Current.Response.ContentType = "application/ms-text";//返回数据类型为text
System.IO.StringWriter sw = new System.IO.StringWriter();
for (int i = 0; i < tb.Rows.Count; i++)
{
for (int j = 0; j < tb.Columns.Count; j++)
{
sw.Write(tb.Rows[i][j].ToString().Trim() + "\t");//列间用制表符
}
sw.Write("\r\n");//行间用换行符
}
HttpContext.Current.Response.Write(sw.ToString());//写入
sw.Close();//关闭流
HttpContext.Current.Response.End();//关闭输出
}

----------------------------------------------------------------------------

//下载Excel

private static void ExportExcel(Stream stm, DataView vw, string sModuleName, int nStartRecord, int nEndRecord)
{
XmlTextWriter xw = new XmlTextWriter(stm, Encoding.UTF8);
xw.Formatting = Formatting.Indented;
xw.IndentChar = ControlChars.Tab;
xw.Indentation = 1;
xw.WriteStartDocument();
xw.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

xw.WriteStartElement("Workbook");
xw.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:spreadsheet");
xw.WriteAttributeString("xmlns:o", "urn:schemas-microsoft-com:office:office");
xw.WriteAttributeString("xmlns:x", "urn:schemas-microsoft-com:office:excel");
xw.WriteAttributeString("xmlns:ss", "urn:schemas-microsoft-com:office:spreadsheet");
xw.WriteAttributeString("xmlns:html", "http://www.w3.org/TR/REC-html40");

xw.WriteStartElement("DocumentProperties");
xw.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:office");
xw.WriteStartElement("Author");
xw.WriteString(Security.FULL_NAME);
xw.WriteEndElement();
xw.WriteStartElement("Created");
//xw.WriteString(DateTime.Now.ToUniversalTime().ToString("s"));
xw.WriteString(DateTime.Now.ToString("s"));
xw.WriteEndElement();
xw.WriteStartElement("Version");
xw.WriteString("11.6568");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteStartElement("ExcelWorkbook");
xw.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:excel");
xw.WriteStartElement("WindowHeight");
xw.WriteString("15465");
xw.WriteEndElement();
xw.WriteStartElement("WindowWidth");
xw.WriteString("23820");
xw.WriteEndElement();
xw.WriteStartElement("WindowTopX");
xw.WriteString("120");
xw.WriteEndElement();
xw.WriteStartElement("WindowTopY");
xw.WriteString("75");
xw.WriteEndElement();
xw.WriteStartElement("ProtectStructure");
xw.WriteString("False");
xw.WriteEndElement();
xw.WriteStartElement("ProtectWindows");
xw.WriteString("False");
xw.WriteEndElement();
xw.WriteEndElement();

xw.WriteStartElement("Styles");
xw.WriteStartElement("Style");
xw.WriteAttributeString("ss:ID", "Default");
xw.WriteAttributeString("ss:Name", "Normal");
xw.WriteStartElement("Alignment");
xw.WriteAttributeString("ss:Vertical", "Bottom");
xw.WriteEndElement();
xw.WriteStartElement("Borders");
xw.WriteEndElement();
xw.WriteStartElement("Font");
xw.WriteEndElement();
xw.WriteStartElement("Interior");
xw.WriteEndElement();
xw.WriteStartElement("NumberFormat");
xw.WriteEndElement();
xw.WriteStartElement("Protection");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteStartElement("Style");
xw.WriteAttributeString("ss:ID", "s21");
xw.WriteStartElement("NumberFormat");
xw.WriteAttributeString("ss:Format", "General Date");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();

DataTable tbl = vw.Table;
xw.WriteStartElement("Worksheet");
xw.WriteAttributeString("ss:Name", sModuleName);
xw.WriteStartElement("Table");
xw.WriteAttributeString("ss:ExpandedColumnCount", tbl.Columns.Count.ToString());
xw.WriteAttributeString("ss:FullColumns" , tbl.Columns.Count.ToString());
// 11/03/2006 Paul. Add one row for the header.
xw.WriteAttributeString("ss:ExpandedRowCount" , (nEndRecord - nStartRecord + 1).ToString());

xw.WriteStartElement("Row");
for ( int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++ )
{
DataColumn col = tbl.Columns[nColumn];
xw.WriteStartElement("Cell");
xw.WriteStartElement("Data");
xw.WriteAttributeString("ss:Type", "String");
//xw.WriteString(col.ColumnName.ToLower());
xw.WriteString(col.ColumnName);
xw.WriteEndElement();
xw.WriteEndElement();
}
xw.WriteEndElement();
for ( int i = nStartRecord; i < nEndRecord; i++ )
{
xw.WriteStartElement("Row");
DataRowView row = vw[i];
for ( int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++ )
{
DataColumn col = tbl.Columns[nColumn];
xw.WriteStartElement("Cell");
// 11/03/2006 Paul. The style must be set in order for a date to be displayed properly.
if ( col.DataType.FullName == "System.DateTime" && row[nColumn] != DBNull.Value )
xw.WriteAttributeString("ss:StyleID", "s21");
xw.WriteStartElement("Data");
if ( row[nColumn] != DBNull.Value )
{
switch ( col.DataType.FullName )
{
case "System.Boolean" :
xw.WriteAttributeString("ss:Type", "String");
xw.WriteString(Sql.ToBoolean (row[nColumn]) ? "1" : "0");
break;
case "System.Single" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToDouble (row[nColumn]).ToString() );
break;
case "System.Double" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToDouble (row[nColumn]).ToString() );
break;
case "System.Int16" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToInteger (row[nColumn]).ToString() );
break;
case "System.Int32" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToInteger (row[nColumn]).ToString() );
break;
case "System.Int64" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToLong (row[nColumn]).ToString() );
break;
case "System.Decimal" :
xw.WriteAttributeString("ss:Type", "Number");
xw.WriteString(Sql.ToDecimal (row[nColumn]).ToString() );
break;
case "System.DateTime":
xw.WriteAttributeString("ss:Type", "DateTime");
//xw.WriteString(Sql.ToDateTime(row[nColumn]).ToUniversalTime().ToString("s"));
xw.WriteString(Sql.ToDateTime(row[nColumn]).ToString("s"));
break;
case "System.Guid" :
xw.WriteAttributeString("ss:Type", "String");
xw.WriteString(Sql.ToGuid (row[nColumn]).ToString().ToUpper());
break;
case "System.String" :
xw.WriteAttributeString("ss:Type", "String");
xw.WriteString(Sql.ToString (row[nColumn]));
break;
case "System.Byte[]" :
{
xw.WriteAttributeString("ss:Type", "String");
byte[] buffer = Sql.ToByteArray((System.Array) row[nColumn]);
xw.WriteBase64(buffer, 0, buffer.Length);
break;
}
default:
// throw(new Exception("Unsupported field type: " + rdr.GetFieldType(nColumn).FullName));
// 11/03/2006 Paul. We need to write the type even for empty cells.
xw.WriteAttributeString("ss:Type", "String");
break;
}
}
else
{
// 11/03/2006 Paul. We need to write the type even for empty cells.
xw.WriteAttributeString("ss:Type", "String");
}
xw.WriteEndElement();
xw.WriteEndElement();
}
xw.WriteEndElement();
}
xw.WriteEndElement(); // Table
xw.WriteStartElement("WorksheetOptions");
xw.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:excel");
xw.WriteStartElement("Selected");
xw.WriteEndElement();
xw.WriteStartElement("ProtectObjects");
xw.WriteString("False");
xw.WriteEndElement();
xw.WriteStartElement("ProtectScenarios");
xw.WriteString("False");
xw.WriteEndElement();
xw.WriteEndElement(); // WorksheetOptions
xw.WriteEndElement(); // Worksheet
xw.WriteEndElement(); // Workbook
xw.WriteEndDocument();
xw.Flush();
}

----------------------------------------------------------------------------

//下载Xml

private static void ExportXml(Stream stm, DataView vw, string sModuleName, int nStartRecord, int nEndRecord)
{
XmlTextWriter xw = new XmlTextWriter(stm, Encoding.UTF8);
xw.Formatting = Formatting.Indented;
xw.IndentChar = ControlChars.Tab;
xw.Indentation = 1;
xw.WriteStartDocument();
xw.WriteStartElement("splendidcrm");

DataTable tbl = vw.Table;
for ( int i = nStartRecord; i < nEndRecord; i++ )
{
xw.WriteStartElement(sModuleName);
DataRowView row = vw[i];
for ( int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++ )
{
DataColumn col = tbl.Columns[nColumn];
//xw.WriteStartElement(col.ColumnName.ToLower());
xw.WriteStartElement(col.ColumnName);
if ( row[nColumn] != DBNull.Value )
{
switch ( col.DataType.FullName )
{
case "System.Boolean" : xw.WriteString(Sql.ToBoolean (row[nColumn]) ? "1" : "0"); break;
case "System.Single" : xw.WriteString(Sql.ToDouble (row[nColumn]).ToString() ); break;
case "System.Double" : xw.WriteString(Sql.ToDouble (row[nColumn]).ToString() ); break;
case "System.Int16" : xw.WriteString(Sql.ToInteger (row[nColumn]).ToString() ); break;
case "System.Int32" : xw.WriteString(Sql.ToInteger (row[nColumn]).ToString() ); break;
case "System.Int64" : xw.WriteString(Sql.ToLong (row[nColumn]).ToString() ); break;
case "System.Decimal" : xw.WriteString(Sql.ToDecimal (row[nColumn]).ToString() ); break;
//case "System.DateTime": xw.WriteString(Sql.ToDateTime(row[nColumn]).ToUniversalTime().ToString(CalendarControl.SqlDateTimeFormat)); break;
case "System.DateTime": xw.WriteString(Sql.ToDateTime(row[nColumn]).ToString(CalendarControl.SqlDateTimeFormat)); break;
case "System.Guid" : xw.WriteString(Sql.ToGuid (row[nColumn]).ToString().ToUpper()); break;
case "System.String" : xw.WriteString(Sql.ToString (row[nColumn])); break;
case "System.Byte[]" :
{
byte[] buffer = Sql.ToByteArray((System.Array) row[nColumn]);
xw.WriteBase64(buffer, 0, buffer.Length);
break;
}
//default:
// throw(new Exception("Unsupported field type: " + rdr.GetFieldType(nColumn).FullName));
}
}
xw.WriteEndElement();
}
xw.WriteEndElement();
}
xw.WriteEndElement();
xw.WriteEndDocument();
xw.Flush();
}

----------------------------------------------------------------------------

//下载Delimited

private static void ExportDelimited(Stream stm, DataView vw, string sModuleName, int nStartRecord, int nEndRecord, char chDelimiter)
{
StreamWriter wt = new StreamWriter(stm);
DataTable tbl = vw.Table;
for ( int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++ )
{
if ( nColumn > 0 )
wt.Write(chDelimiter);
DataColumn col = tbl.Columns[nColumn];
//wt.Write(col.ColumnName.ToLower());
wt.Write(col.ColumnName);
}
wt.WriteLine("");

for ( int i = nStartRecord; i < nEndRecord; i++ )
{
DataRowView row = vw[i];
for ( int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++ )
{
if ( nColumn > 0 )
wt.Write(chDelimiter);
DataColumn col = tbl.Columns[nColumn];
if ( row[nColumn] != DBNull.Value )
{
string sValue = String.Empty;
switch ( col.DataType.FullName )
{
case "System.Boolean" : sValue = Sql.ToBoolean (row[nColumn]) ? "1" : "0"; break;
case "System.Single" : sValue = Sql.ToDouble (row[nColumn]).ToString() ; break;
case "System.Double" : sValue = Sql.ToDouble (row[nColumn]).ToString() ; break;
case "System.Int16" : sValue = Sql.ToInteger (row[nColumn]).ToString() ; break;
case "System.Int32" : sValue = Sql.ToInteger (row[nColumn]).ToString() ; break;
case "System.Int64" : sValue = Sql.ToLong (row[nColumn]).ToString() ; break;
case "System.Decimal" : sValue = Sql.ToDecimal (row[nColumn]).ToString() ; break;
//case "System.DateTime": sValue = Sql.ToDateTime(row[nColumn]).ToUniversalTime().ToString(CalendarControl.SqlDateTimeFormat); break;
case "System.DateTime": sValue = Sql.ToDateTime(row[nColumn]).ToString(CalendarControl.SqlDateTimeFormat); break;
case "System.Guid" : sValue = Sql.ToGuid (row[nColumn]).ToString().ToUpper(); break;
case "System.String" : sValue = Sql.ToString (row[nColumn]); break;
case "System.Byte[]" :
{
byte[] buffer = Sql.ToByteArray((System.Array) row[0]);
sValue = Convert.ToBase64String(buffer, 0, buffer.Length);
break;
}
//default:
// throw(new Exception("Unsupported field type: " + rdr.GetFieldType(nColumn).FullName));
}
if( sValue.IndexOf(chDelimiter) >= 0 || sValue.IndexOf('\"') >= 0 )
sValue = "\"" + sValue.Replace("\"", "\"\"") + "\"";
wt.Write(sValue);
}
}
wt.WriteLine("");
}
wt.Flush();
}

----------------------------------------------------------------------------

//下载 通用

public static void Export(DataView vw, string sModuleName, string sExportFormat, string sExportRange, int nCurrentPage, int nPageSize, string[] arrID, bool bDeleteIDColumn)
{
int nStartRecord = 0;
int nEndRecord = vw.Count;
switch (sExportRange)
{
case "Page":
nStartRecord = nCurrentPage * nPageSize;
nEndRecord = Math.Min(nStartRecord + nPageSize, vw.Count);
break;
case "Selected":
{
// 10/17/2006 Paul. There must be one selected record to continue.
if (arrID == null)
{
L10N L10n = HttpContext.Current.Items["L10n"] as L10N;
throw (new Exception(L10n.Term(".LBL_LISTVIEW_NO_SELECTED")));
}
StringBuilder sbIDs = new StringBuilder();
int nCount = 0;
foreach (string item in arrID)
{
if (nCount > 0)
sbIDs.Append(" or ");
sbIDs.Append("ID = \'" + item.Replace("\'", "\'\'") + "\'" + ControlChars.CrLf);
nCount++;
}
//vw.RowFilter = "ID in (" + sbIDs.ToString() + ")";
// 11/03/2006 Paul. A filter might already exist, so make sure to maintain the existing filter.
if (vw.RowFilter.Length > 0)
vw.RowFilter = " and (" + sbIDs.ToString() + ")";
else
vw.RowFilter = sbIDs.ToString();
nEndRecord = vw.Count;
break;
}
}

// 04/28/2009 baiyin. Delete the "ID" columns
//start
if (vw != null && bDeleteIDColumn)
{
DataTable tbl = vw.Table;
for (int nColumn = 0; nColumn < tbl.Columns.Count; nColumn++)
{
DataColumn col = tbl.Columns[nColumn];
if (col.ColumnName == "ID")
{
//vw.Table.Columns.RemoveAt(nColumn);
vw.Table.Columns.Remove("ID");
break;
}
}
}
//end

HttpResponse Response = HttpContext.Current.Response;
StringBuilder sb = new StringBuilder();
switch (sExportFormat)
{
case "csv":
Response.ContentType = "text/csv";
// 08/06/2008 yxy21969. Make sure to encode all URLs.
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(sModuleName + ".csv"));
ExportDelimited(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord, ',');
Response.End();
break;
case "tab":
Response.ContentType = "text/txt";
// 08/06/2008 yxy21969. Make sure to encode all URLs.
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(sModuleName + ".txt"));
ExportDelimited(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord, '\t');
Response.End();
break;
case "xml":
Response.ContentType = "text/xml";
// 08/06/2008 yxy21969. Make sure to encode all URLs.
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(sModuleName + ".xml"));
ExportXml(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord);
Response.End();
break;
//case "Excel":
default:
Response.ContentType = "application/vnd.ms-excel";
// 08/06/2008 yxy21969. Make sure to encode all URLs.
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(sModuleName + ".xls"));
ExportExcel(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord);
Response.End();
break;
}
//vw.RowFilter = null;
}
//end

//-----------------------------------------------------------------------------------------------------------------------------------

来自http://blog.csdn.net/lansetiankong12/article/details/50634573

C#文件下载的四种方法~有文件流,有WriteFile等

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
{
protected void Page_Load(object sender, EventArgs e)
{

}

//TransmitFile实现下载
protected void Button1_Click(object sender, EventArgs e)
{
/*
微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
代码如下:
*/

Response.ContentType = "application/x-zip-compressed";
string FileName = "test.doc";
//使用UTF-8对文件名进行编码
Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + "\"");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
string filename = Server.MapPath("../ReportTemplate/test.doc");
Response.TransmitFile(filename);
}

//WriteFile实现下载
protected void Button2_Click(object sender, EventArgs e)
{
/*
using System.IO;
*/
string fileName = "test.doc";//客户端保存的文件名
string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}

//WriteFile分块下载  当文件过大时候,最好是采用分块下载,避免内存溢出的问题
protected void Button3_Click(object sender, EventArgs e)
{
string fileName = "test.doc";//客户端保存的文件名
string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径


System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);


if (fileInfo.Exists == true)
{
const long ChunkSize = 102400; //100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
byte[] buffer = new byte[ChunkSize];


Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length; //获取下载的文件总大小
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize)); //读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
Response.Close();
}
}

//流方式下载
protected void Button4_Click(object sender, EventArgs e)
{
string fileName = "test.doc";//客户端保存的文件名
string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径

//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}

posted @ 2016-11-22 10:16  黑色鼠标  阅读(232)  评论(0编辑  收藏  举报