花费一下午,从各大博主的代码当中总算是把这个功能给实现了,主要的目的是让大家明白原理。如果出现大佬代码被我爬进来了,需要删除的滴滴我哦。还有就是主要所有的代码看不懂的记得看注释,比较更多的都是写在代码的注释里的。
先把前端的跟点击事件贴一下吧
划重点,前端有哪些东西呢?
然后是第一段代码段
///
/// 点击读取按钮执行
///
///
///
protected void Button1_Click(object sender, EventArgs e)
{
//数据表不解释
DataTable dt;
//执行方法读取数据表。
dt = ExcelToDataTable();
//读取后防止回发先存着待会转excel的时候用!
ViewState["dt"] = dt;
//控件填充
GridView1.DataSource = dt;
GridView1.DataBind();
}
///
/// 读取excel转化成datatable
///
///
///
public DataTable ExcelToDataTable()
{
//别问我这个干嘛的,一下想不起来了
string sheetName;
//获取上传控件
FileUpload fileUpload = fuload;
//HasFile看看控件是不是选好文件了,没有就抬走
if (!fileUpload.HasFile)
{
return null;
}
//把你上传的表放进服务里面去,待会用
string path = HttpContext.Current.Server.MapPath(@"~/temp/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(fileUpload.FileName);
fileUpload.SaveAs(path + newFileName);
//数据库方面的就是把excel当成一个数据库,然后开始生成与创建连接字符串
string strConn = string.Empty;
switch (Path.GetExtension(fileUpload.FileName))
{
case ".xlsx":
strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + path + newFileName + ";Extended Properties='Excel 12.0 Xml; HDR=YES; IMEX=1'";
break;
case ".xls":
strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + path + newFileName + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
break;
default:
return null;
}
try
{
//创建数据源链接对象,添加连接字符串,然后打开
OleDbConnection conn1 = new OleDbConnection(strConn);
conn1.Open();
//获取表基本信息
DataTable dtSheetName = conn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//把excel底下的附表名获取到,然后关闭
string[] strTableNames = new string[dtSheetName.Rows.Count];
sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();
conn1.Close();
conn1.Dispose();
//然后开始查询表
DataTable dtTemp = new DataTable();
string strExcelTemp = string.Format("select top 1 * from [{0}]", sheetName);
//后面的代码自己去理解吧,查出来以后返回datatable
DataTable dt = new DataTable();
string strExcel = string.Format("select * from [{0}]", sheetName);
using (OleDbConnection conn = new OleDbConnection(strConn))
{
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcelTemp, strConn.Replace("HDR=YES", "HDR=NO")))
{
myCommand.Fill(dtTemp);
}
if (dtTemp != null && dtTemp.Rows.Count == 1)
{
//前三列不为空
strExcel += " where " + dtTemp.Rows[0][0] + " is not null and " + dtTemp.Rows[0][1] + " is not null and " + dtTemp.Rows[0][0] + " is not null ";
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn))
{
myCommand.Fill(dt);
}
}
else
{
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn))
{
myCommand.Fill(dt);
}
}
}
return dt;
}
catch (Exception e)
{
return null;
}
finally
{
if (File.Exists(path + newFileName))
{
File.Delete(path + newFileName);
}
}
}
前面的部分就是读取Excel数据用的,读取完后将读出来的DataTable填充到了GridView里面。接下来则是将他读取出来生成Excel表重新保存到指定的路径去。
///
/// 点击生成Excel文件并且打它
///
///
///
protected void Button1_Click1(object sender, EventArgs e)
{
//重点就是这个ViewState["dt"],别问我哪里来的,就在上一个方法中存下来的
string dizhi =DataToExcel((DataTable)ViewState["dt"], "1");
//后面的代码就是打开指定文件的自己看
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
//info.WorkingDirectory = Application.StartupPath;
info.FileName = dizhi;
info.Arguments = "";
try
{
System.Diagnostics.Process.Start(info);
}
catch (System.ComponentModel.Win32Exception we)
{
return;
}
}
///
/// Datatable生成Excel表格并返回路径
///
/// Datatable
/// 文件名
///
public string DataToExcel(DataTable m_DataTable, string s_FileName)
{
//显示设置路径嘛,为了方便,直接放d盘下吧
string FileName = "d:/" + s_FileName + ".xls";
//然后是判断这个文件是不是存在,如果存在,删除,不存在,过
if (File.Exists(FileName))
{
File.Delete(FileName);
}
//下面是一系列的读写代码,直接拷贝吧
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "";
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, Encoding.Unicode);
//先把第一行拿出来,这是标题
for (int i = 0; i < m_DataTable.Columns.Count; i++)
{
strLine = strLine + m_DataTable.Columns[i].Caption.ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
//然后再循环一次,把内容填充进去
for (int i = 0; i < m_DataTable.Rows.Count; i++)
{
for (int j = 0; j < m_DataTable.Columns.Count; j++)
{
if (m_DataTable.Rows[i].ItemArray[j] == null)
strLine = strLine + " " + Convert.ToChar(9);
else
{
string rowstr = "";
rowstr = m_DataTable.Rows[i].ItemArray[j].ToString();
if (rowstr.IndexOf("\r\n") > 0)
rowstr = rowstr.Replace("\r\n", " ");
if (rowstr.IndexOf("\t") > 0)
rowstr = rowstr.Replace("\t", " ");
strLine = strLine + rowstr + Convert.ToChar(9);
}
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
objStreamWriter.Close();
objFileStream.Close();
//填充完后关闭读写流,将刚刚的路径给放回就行了
return FileName;
}
就这样,就结束了,自己看吧,不懂再说。