步骤1:导入NOIO.dll (我导入压缩包中的4.0)
下载地址:http://npoi.codeplex.com/downloads/get/1572743
步骤二:粘贴代码(^ .... ^)
public class ExeclController : Controller
{
//
// GET: /Execl/
public ActionResult Index()
{
DataTable dt = new DataTable("AllVehSite");
DataColumnCollection columns = dt.Columns;
columns.Add("AcctId", typeof(System.Int32));
columns.Add("SiteId", typeof(System.Int32));
columns.Add("DbType", typeof(System.String));
columns.Add("ConnStr", typeof(System.String));
DataRow datarow = dt.NewRow();
datarow["AcctId"] = 1;
datarow["SiteId"] = 2;
datarow["DbType"] = "2";
datarow["ConnStr"] = "1";
dt.Rows.Add(datarow);
WriteExcel(dt, @"C:\Users\Administrator\Desktop\datas111.xls");
return View();
}
#region 导出Execl
public static void WriteExcel(DataTable dt, string filePath)
{
if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
}
}
// 写入到客户端
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
book.Write(ms);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
book.Close();
book = null;
}
}
}
#endregion
}
步骤3:修改路径,Databable