---
title: "C#向excel中写入数据的三种方式"
author: "soboer"
date: "2011-11-30T10:47:00Z"
tags: []
slug: "c-excel"
draft: false
lastmod: "2011-11-30T16:11:42Z"
id: 1285997
url: "https://soboer.iteye.com/blog/1285997"
---

**第一种：将DataGrid中的数据以流的形式写到excel中，格式以html的形式存在**

Response.Clear();  
Response.Buffer = true;  
Response.Charset = "GB2312";  
Response.AppendHeader("Content-Disposition", "attachment;filename=DialoutTemplate.xls");

// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码！！！  
Response.ContentEncoding = System.Text.Encoding.UTF8;  
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。

//Response.ContentType = "application/vnd.ms-excel";//输出类型  
//Response.Charset = "";

//关闭 ViewState  
EnableViewState = false;  
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串  
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。  
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能  
//获取control的HTML

dg.RenderControl(hw);//将table中的内容输出到HtmlTextWriter对象中

// 把HTML写回浏览器  
Response.Write(tw.ToString());  
Response.Flush();  
Response.End();

**第二种：将数据源中的数据以文件流的形式写到excel中，格式以txt的形式存在**

FileStream fs = new FileStream(Server.MapPath("report\_export/DialoutTemplate.xls"), FileMode.Create, FileAccess.Write);  
StreamWriter rw = new StreamWriter(fs, Encoding.Default);//建立StreamWriter为写作准备;

DataTable dt = GetDataTableSource();

int count = dt.Columns.Count;  
string head = "";  
string values = "";

for (int i = 0; i &lt; count; i++)  
{  
string h = dt.Columns\[i].ColumnName + "\\t";  
string v = dt.Rows\[0]\[i].ToString() + "\\t";

head += h;  
values += v;  
}  
rw.WriteLine(head);  
rw.WriteLine(values);

rw.Close();  
fs.Close();

Response.Redirect("report\_export/DialoutTemplate.xls");

**第三种：将数据源中的数据直接写到excel中，格式以xls形式存在，好处导出的**

**数据可以直接导入，可以将数字格式自动转化为文本格式，可以减少**

**格式转化的繁琐环节，还可以预留将数字转换为文本的格式的行数，**

**可以完全自定义**

Excel.Application xlApp;  
Excel.Workbook xlBook;  
Excel.Workbooks xlBooks;  
//Excel.Range xlRange;  
Excel.Sheets xlsheets;  
Excel.Worksheet xlSheet;  
int k = 0;  
try  
{  
string strCurrentPath = Server.MapPath("report\_export/DialoutTemplate.xls");  
string FilePath = strCurrentPath;

FileInfo fi = new FileInfo(FilePath);  
if (fi.Exists) //判断文件是否已经存在,如果存在就删除!  
{  
fi.Delete();  
}

xlApp = new Excel.Application();  
xlBooks = xlApp.Workbooks;  
xlBook = xlBooks.Add(Type.Missing);  
xlsheets = xlBook.Worksheets;  
IntPtr intptr = new IntPtr(xlApp.Hwnd);  
xlSheet = (Excel.Worksheet)xlsheets.get\_Item(1);

DataTable dt = GetDataTableSource();

int count = dt.Columns.Count;  
for (int i = 0; i &lt; count; i++)  
{  
string h = dt.Columns\[i].ColumnName;  
string v = dt.Rows\[0]\[i].ToString();

((Excel.Range)xlSheet.Cells\[1, i + 1]).Value2 = h;  
Excel.Range r1 = xlSheet.get\_Range(xlSheet.Cells\[1, 1], xlSheet.Cells\[1, i + 1]);  
r1.NumberFormatLocal = "@";  
((Excel.Range)xlSheet.Cells\[2, i + 1]).Value2 = v;

Excel.Range r2 = xlSheet.get\_Range(xlSheet.Cells\[2, 1], xlSheet.Cells\[2, i + 1]);  
r2.NumberFormatLocal = "@";  
}

for (int j = 1; j &lt; 500; j++)  
{  
Excel.Range r = xlSheet.get\_Range(xlSheet.Cells\[2 + j, 1], xlSheet.Cells\[2 + j, count]);  
r.NumberFormatLocal = "@";  
}

xlBook.SaveAs(FilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  
xlBook.Close(false, Type.Missing, Type.Missing);  
xlBooks.Close();  
xlApp.Quit();  
Response.Redirect("report\_export/DialoutTemplate.xls");  
GetWindowThreadProcessId(intptr, out k);  
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);  
p.Kill();

}  
catch (Exception ex)  
{  
Response.Write(ex.Message);  
}  
finally  
{  
//xlRange = null;  
xlSheet = null;  
xlBook = null;  
xlApp = null;  
}