码迷,mamicode.com
首页 > 其他好文 > 详细

Excel导入DataTable兼容2003-2012(请细心查看注释)以及 DataTable导出Excel(导出格式2003.xls)注释:需要引用NPOI

时间:2015-01-28 12:49:21      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

1、#region Excel导入DataTable兼容2003-2012(请细心查看注释)
/// <summary> 
/// 读取Excel文件到DataSet中
/// 注释1:2012导出如报错“ System.InvalidOperationException: 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序。”解决:下载2007 Office system 驱动程序:数据连接组件安装http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe

/// </summary> 
/// <param name="filePath">文件路径</param> 
/// <returns></returns> 
public static DataSet ToDataTable(string filePath)
{
string connStr = "";
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;

if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
string sql_F = "Select * FROM [{0}]";
//string sql_F = "Select * FROM [K_rt$A:K]";
OleDbConnection conn = null;
OleDbDataAdapter da = null;
DataTable dtSheetName = null;

DataSet ds = new DataSet();
try
{
// 初始化连接,并打开 
conn = new OleDbConnection(connStr);
conn.Open();

// 获取数据源的表定义元数据 
string SheetName = "";
dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

// 初始化适配器 
da = new OleDbDataAdapter();
for (int i = 0; i < dtSheetName.Rows.Count; i++)
{
SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];

if (SheetName.Contains("$") && !SheetName.Replace("‘", "").EndsWith("$"))
{
continue;
}

da.SelectCommand = new OleDbCommand(String.Format("SELECT * FROM [" + SheetName + "A:IU]", SheetName), conn);
DataSet dsItem = new DataSet();
da.Fill(dsItem, SheetName);

ds.Tables.Add(dsItem.Tables[0].Copy());
}
}
catch (Exception ex)
{
}
finally
{
// 关闭连接 
if (conn.State == ConnectionState.Open)
{
conn.Close();
da.Dispose();
conn.Dispose();
}
}
return ds;
}
#endregion


2、#region DataTable导出Excel(导出格式2003.xls)注释:需要引用NPOI
/// <summary>
/// DataTable导出Excel
/// </summary>
/// <param name="dt">DataTable</param>
public void private_export(DataTable dt)
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("数据");
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
//列名
row1.CreateCell(0).SetCellValue("序号");
row1.CreateCell(1).SetCellValue("机型");
row1.CreateCell(2).SetCellValue("价格");
row1.CreateCell(3).SetCellValue("本月回收次数");
//循环DataTable中的字段
for (int i = 0; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
rowtemp.CreateCell(0).SetCellValue(dt.Rows[i]["ID"].ToString());
rowtemp.CreateCell(1).SetCellValue(dt.Rows[i]["Model"].ToString());
rowtemp.CreateCell(2).SetCellValue(dt.Rows[i]["Price"].ToString());
rowtemp.CreateCell(3).SetCellValue(dt.Rows[i]["Count"].ToString());

}
for (int columnNum = 0; columnNum < sheet1.LastRowNum; columnNum++)
{
int columnWidth = sheet1.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet1.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过 
if (sheet1.GetRow(rowNum) == null)
{
currentRow = sheet1.CreateRow(rowNum);
}
else
{
currentRow = sheet1.GetRow(rowNum);
}

if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
//格式
//ICellStyle style = book.CreateCellStyle();
//style.Alignment = HorizontalAlignment.Center;
//style.VerticalAlignment = VerticalAlignment.Center;
//sheet1.GetRow(columnNum).GetCell(rowNum).CellStyle = style;
}
if (columnWidth > 200)
{
sheet1.SetColumnWidth(columnNum, columnWidth * 156);
}
if (columnWidth < 200)
{
sheet1.SetColumnWidth(columnNum, columnWidth * 256);
}
}
string path = Server.MapPath(DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
using (FileStream fs = new FileStream(path, FileMode.Create))
{
book.Write(fs);
}
DownLoadFile(path);
}
/// <summary>
/// 导出后下载Excel文件
/// </summary>
/// <param name="fileURL">文件的路径</param>
public void DownLoadFile(string fileURL)
{
//string fileURL = this.Server.MapPath("你要下载的文件路径");//文件路径,可用相对路径
FileInfo fileInfo = new FileInfo(fileURL);
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode(fileInfo.Name.ToString()));
//文件名
Response.AddHeader("content-length", fileInfo.Length.ToString());
//文件大小
//lbtnPriceFiltrate.Enabled=
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.Default; Response.WriteFile(fileURL);
}
#endregion

Excel导入DataTable兼容2003-2012(请细心查看注释)以及 DataTable导出Excel(导出格式2003.xls)注释:需要引用NPOI

标签:

原文地址:http://www.cnblogs.com/wangjian0619/p/4255321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!