Excel 导出和导入操作
导出
Code
//定义方法GetData(),返回一个数据表
protected DataSet GetData()
{
//建立连接
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrCon"].ConnectionString);
con.Open();
string sqlstr = "select CarrierID,CName,EName,Code,DiscountRatio,DiscountValue,ImageURL,FullName from ConstantCarrier";
//SqlCommand cmd = new SqlCommand(sqlstr,con);
SqlDataAdapter sda = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
sda.Fill(ds, "excel");
con.Close();
return ds;
}
//生成Excel文件的代码
protected void ExportExcel()
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); // 创建工作簿
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1]; // 创建工作页
DataSet ds = GetData();
int iMaxRow = ds.Tables["Excel"].Rows.Count;
int iMaxCol = ds.Tables["Excel"].Columns.Count;
// 设置格式
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Name = "黑体";
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Bold = true;
ws.get_Range(ws.Cells[1, 1], ws.Cells[iMaxRow + 1, iMaxCol]).Borders.LineStyle = 1;
// 设置标题
excel.Cells[1, 1] = "CarrierID";
excel.Cells[1, 2] = "CName";
excel.Cells[1, 3] = "EName";
excel.Cells[1, 4] = "Code";
excel.Cells[1, 5] = "DiscountRatio";
excel.Cells[1, 6] = "DiscountValue";
excel.Cells[1, 7] = "ImageURL";
excel.Cells[1, 8] = "FullName";
// 填充数据
for (int iRow = 0; iRow < iMaxRow; iRow++)
{
for (int iCol = 0; iCol < iMaxCol; iCol++)
{
excel.Cells[iRow + 2, iCol + 1] = ds.Tables["Excel"].Rows[iRow][iCol].ToString();
}
}
// 保存Excel
excel.Save(txtexcel.Text.Trim());
// 打开Excel
excel.Visible = true;
}
//导出到Excel按钮
protected void Button1_Click1(object sender, EventArgs e)
{
ExportExcel();
}
导入//定义方法GetData(),返回一个数据表
protected DataSet GetData()
{
//建立连接
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrCon"].ConnectionString);
con.Open();
string sqlstr = "select CarrierID,CName,EName,Code,DiscountRatio,DiscountValue,ImageURL,FullName from ConstantCarrier";
//SqlCommand cmd = new SqlCommand(sqlstr,con);
SqlDataAdapter sda = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
sda.Fill(ds, "excel");
con.Close();
return ds;
}
//生成Excel文件的代码
protected void ExportExcel()
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); // 创建工作簿
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1]; // 创建工作页
DataSet ds = GetData();
int iMaxRow = ds.Tables["Excel"].Rows.Count;
int iMaxCol = ds.Tables["Excel"].Columns.Count;
// 设置格式
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Name = "黑体";
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Bold = true;
ws.get_Range(ws.Cells[1, 1], ws.Cells[iMaxRow + 1, iMaxCol]).Borders.LineStyle = 1;
// 设置标题
excel.Cells[1, 1] = "CarrierID";
excel.Cells[1, 2] = "CName";
excel.Cells[1, 3] = "EName";
excel.Cells[1, 4] = "Code";
excel.Cells[1, 5] = "DiscountRatio";
excel.Cells[1, 6] = "DiscountValue";
excel.Cells[1, 7] = "ImageURL";
excel.Cells[1, 8] = "FullName";
// 填充数据
for (int iRow = 0; iRow < iMaxRow; iRow++)
{
for (int iCol = 0; iCol < iMaxCol; iCol++)
{
excel.Cells[iRow + 2, iCol + 1] = ds.Tables["Excel"].Rows[iRow][iCol].ToString();
}
}
// 保存Excel
excel.Save(txtexcel.Text.Trim());
// 打开Excel
excel.Visible = true;
}
//导出到Excel按钮
protected void Button1_Click1(object sender, EventArgs e)
{
ExportExcel();
}
Code
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile file = this.FileUpload1.PostedFile;//获得要上传的文件
string fileName = System.IO.Path.GetFileName(file.FileName);//获取文件的名称
if (fileName == "")
{
Response.Write("<script>alert('请选择导入的文件');</script>");
}
else
{
string ExcelHz = System.IO.Path.GetExtension(FileUpload1.FileName);
if (ExcelHz != ".xls")
{
Response.Write("请上传Excel文件的格式");
}
else
{
file.SaveAs(System.Web.HttpContext.Current.Request.MapPath("upload/") + fileName);
// Session["fileName"] = fileName;
//获取excel问里的sheet1,sheet2,sheet3,文件名组。
string[] name = new string[1000];
Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
object miss = System.Reflection.Missing.Value;
Workbook wbs = excel.Workbooks.Open(Server.MapPath("upload/" + fileName), miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
for (int i = 1; i <= wbs.Worksheets.Count; i++)
{
Worksheet sheet = (Worksheet)excel.Sheets.get_Item(i);
name[i] = sheet.Name;
NewMethod(fileName, name[i]);
}
excel.ActiveWorkbook.Close(false, null, null);
Response.Write("<script>alert('成功');</script>");
}
}
}
/// <summary>
/// 将excel导入数据库的方法
/// </summary>
/// <param name="fileName">excel的文件名</param>
/// <param name="TableName">excel表的名字</param>
private void NewMethod(string fileName, string TableName)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("upload/" + fileName) + ";Extended Properties='Excel 5.0;HDR=YES;IMEX=1'");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + TableName + "$]", conn);
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConQ"].ToString());
//string sqldata = "select * from ConstantAirPort";
//DataSet ds = DBHelper.Query(sqldata);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string AirportID = ds.Tables[0].Rows[i]["AirportID"].ToString(); //姓名
string CName = ds.Tables[0].Rows[i]["CName"].ToString();//性别
string EName = ds.Tables[0].Rows[i]["EName"].ToString();//年龄
string Code = ds.Tables[0].Rows[i]["Code"].ToString();//年龄
string CityID = ds.Tables[0].Rows[i]["CityID"].ToString();//年龄
string CityCName = ds.Tables[0].Rows[i]["CityCName"].ToString();//年龄
string FullName = ds.Tables[0].Rows[i]["FullName"].ToString();//年龄
string sql = "insert into ConstantAirPort(AirportID,CName,EName,Code,CityID,CityCName,FullName) values('" + AirportID + "','" + CName + "','" + EName + "','" + Code + "','" + CityID + "','" + CityCName + "','" + FullName + "')";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConQ"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile file = this.FileUpload1.PostedFile;//获得要上传的文件
string fileName = System.IO.Path.GetFileName(file.FileName);//获取文件的名称
if (fileName == "")
{
Response.Write("<script>alert('请选择导入的文件');</script>");
}
else
{
string ExcelHz = System.IO.Path.GetExtension(FileUpload1.FileName);
if (ExcelHz != ".xls")
{
Response.Write("请上传Excel文件的格式");
}
else
{
file.SaveAs(System.Web.HttpContext.Current.Request.MapPath("upload/") + fileName);
// Session["fileName"] = fileName;
//获取excel问里的sheet1,sheet2,sheet3,文件名组。
string[] name = new string[1000];
Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
object miss = System.Reflection.Missing.Value;
Workbook wbs = excel.Workbooks.Open(Server.MapPath("upload/" + fileName), miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
for (int i = 1; i <= wbs.Worksheets.Count; i++)
{
Worksheet sheet = (Worksheet)excel.Sheets.get_Item(i);
name[i] = sheet.Name;
NewMethod(fileName, name[i]);
}
excel.ActiveWorkbook.Close(false, null, null);
Response.Write("<script>alert('成功');</script>");
}
}
}
/// <summary>
/// 将excel导入数据库的方法
/// </summary>
/// <param name="fileName">excel的文件名</param>
/// <param name="TableName">excel表的名字</param>
private void NewMethod(string fileName, string TableName)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("upload/" + fileName) + ";Extended Properties='Excel 5.0;HDR=YES;IMEX=1'");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + TableName + "$]", conn);
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConQ"].ToString());
//string sqldata = "select * from ConstantAirPort";
//DataSet ds = DBHelper.Query(sqldata);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string AirportID = ds.Tables[0].Rows[i]["AirportID"].ToString(); //姓名
string CName = ds.Tables[0].Rows[i]["CName"].ToString();//性别
string EName = ds.Tables[0].Rows[i]["EName"].ToString();//年龄
string Code = ds.Tables[0].Rows[i]["Code"].ToString();//年龄
string CityID = ds.Tables[0].Rows[i]["CityID"].ToString();//年龄
string CityCName = ds.Tables[0].Rows[i]["CityCName"].ToString();//年龄
string FullName = ds.Tables[0].Rows[i]["FullName"].ToString();//年龄
string sql = "insert into ConstantAirPort(AirportID,CName,EName,Code,CityID,CityCName,FullName) values('" + AirportID + "','" + CName + "','" + EName + "','" + Code + "','" + CityID + "','" + CityCName + "','" + FullName + "')";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConQ"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
}