1、 导入操作
要做一个类似下面界面的网页,里面有导入csv文件的操作。
查找了一些简单资料,写了如下代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary>
/// 点击导入按钮,进行相应的处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnImport_Click(object sender, EventArgs e)
{
if (flup.HasFile)//判断是否有文件要上传
{
string fileName = Server.MapPath("phoneNums.csv");//文件物理路径
flup.SaveAs(fileName);//上传到服务器上
if (File.Exists(fileName))//检测文件上传是否成功
{
StreamReader sr;
string strTol = string.Empty;
string strTemp = string.Empty;
int count = 0;//导入成功的计数
try
{
sr = new StreamReader(fileName, Encoding.GetEncoding("gb2312"));
strTemp = sr.ReadLine();//跳过头部
strTemp = sr.ReadLine();//跳过模板号码
strTemp = sr.ReadLine();//第一行号码
while (!string.IsNullOrEmpty(strTemp))//如果还有数据,继续读数据
{
count++;
strTol += strTemp + ",";
strTemp = sr.ReadLine();//读取下一行
}
}
catch (Exception)
{
throw;
}
sr.Close();//关闭流
txtPhone.Text += strTol.Substring(0,strTol.Length-1);
lblSuccess.Text = "成功导入:"+count.ToString()+"个";
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), null, "<script>alert('文件上传失败,请尝试重新上传!')</script>", false);
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), null, "<script>alert('请选择文件后上传!')</script>", false);
}
}
2、导出操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
string fileHeader = "序号,时间,号码,归属地,状态,金额";//导出格式
StringWriter sw = new StringWriter();//创建流
sw.WriteLine(fileHeader);//把导出格式写入流
string fileName = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + ".csv";//保存文件名
string param = "";
//从数据库中取出数据
DataTable dt = SqlHelper.GetTabel("Amount_Time,PhoneNum,Area_Code,Is_Success,Amount", "CRP_Business_OrderInfo", m_where, "report");
if (dt != null)
{
int cnt = 0;
//用循环把数据一行行输出到缓冲流中
for (int j = 0; j < dt.Rows.Count; j++)
{
param = (++cnt).ToString() + ",";
for (int i = 0; i < dt.Columns.Count; i++)
{
string colName = dt.Columns[i].ToString();
if (colName == "Is_Success")
{
string state = dt.Rows[j][i].ToString();
if (state == "2")
{
param += "成功";
}
else if (state == "1" || state == "0")
{
param += "处理中";
}
else
{
param += "失败";
}
param += ",";
}
//归属地
else if (colName == "Area_Code")
{
DataRow dr_areaName = Northwind.GetAreaName(dt.Rows[j][i].ToString());
if (dr_areaName != null)
{
param += dr_areaName["Area_Name"].ToString();
param += ",";
}
}
else
{
param += dt.Rows[j][i].ToString();
param += ",";
}
}
sw.WriteLine(param);//一行行输出
}
}
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);//将http标题添加到输出流
HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出的http MIME类型为文件输出
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出的http字符集
HttpContext.Current.Response.Write(sw);//写入http响应流
sw.Close();//关闭流
HttpContext.Current.Response.End();//将当前所有缓冲的输出发送到客户端,停止该页的执行