大家好,
现在我有两个Excel知道存放地址,使用C#把Excel.xls进行复制给Exce2l.xls 使用OleDb能进行操作吗,大家帮忙看一下~
把两个EXCEL都导入DataTable中,然后进行合并,再输出新的Excel,或覆盖“Exce2l.xls”。
#region 导入Excel文件
public static DataTable ImportExcel(string filePathName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath(filePathName) + ";Extended Properties=Excel 8.0";
//链接Excel
OleDbConnection cnnxls = new OleDbConnection(strConn);
//读取Excel里面有 表Sheet1
string abc = filePathName.Substring(filePathName.LastIndexOf("/") + 1);
OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + abc + "$]", cnnxls);
DataSet ds = new DataSet();
//将Excel里面有表内容装载到内存表中!
oda.Fill(ds);
return ds.Tables[0];
}
#endregion
#region 根据传入的DataTable并导出为Excel文件(无HTML装饰)
/// <summary>
/// 根据传入的DataTable并导出为Excel文件
/// </summary>
/// <param name="dt">传入的DataTable</param>
/// <param name="fileName">文件名</param>
public static void ExportExcel(DataTable dt, string fileName)
{
if (dt == null || dt.Rows.Count == 0) { return; }
HttpContext.Current.Response.Clear();
//Encoding pageEncode = Encoding.GetEncoding(PageEncode);
HttpContext.Current.Response.Charset = "gb2312";
//Response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
//Response.ContentType = "application/x-octet-stream";//"application/vnd.ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";//"text/csv";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
System.IO.StringWriter oSW = new System.IO.StringWriter();
HtmlTextWriter oHW = new HtmlTextWriter(oSW);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(oHW);
HttpContext.Current.Response.Write(oSW.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
#endregion
你的 Excel 有模板,并且要保持格式?你只有用 Excel 互操作了,因为 OLEDB 只关心数据。Excel 有 Copy/Paste Sheet 之类的功能,你可以用互操作进行。