1.首先需要引用 Newtonsoft.Json 目的是为了把对象类直接转换为JSON,返回到前台
using Newtonsoft.Json;
2.定义一个类,存储返回的值
public class Result
{
/// <summary>
/// 返回结果 bz 0表示操作失败 1表示操作成功
/// </summary>
public int Bz { get; set; }
/// <summary>
/// 错误说明
/// </summary>
public string Err { get; set; }
}
3.接收csv 并开始解析csv的内容 通过下面的操作 把可以转换的值转换到DataTable中 然后从DataTable中处理数据
private void JyUploadFile(HttpContext context)
{
Result res = new Result();
if (context.Request.Files == null || context.Request.Files[0] == null)
{
res.Bz = 0;
res.Err = "当前未选择文件!";
}
else
{
HttpPostedFile XlsFile = context.Request.Files[0];
int nFileLength = XlsFile.ContentLength;
if (nFileLength == 0)
{
res.Bz = 0;
res.Err = "当前选择的文件无数据!";
}
else
{
string Exten = Path.GetExtension(XlsFile.FileName).ToUpper();
if (Exten != ".CSV")
{
res.Bz = 0;
res.Err = "选择的文件不正确,请选择CSV!";
}
else
{
//这个字段中存储了很列名称的转换,可以吧列名做一个对应关系
Dictionary<string, string> BaiDu = new Dictionary<string, string>();
string path = CreateFolder(DateTime.Now.ToString("yyyyMMdd"));
string file = path + "\\" + Path.GetFileName(XlsFile.FileName);
try
{
#region 对于文件的解析处理 文件解析若是失败 应该会抛错
//这个需要把文件存储一下 存储到应用服务器,因上传是本地,若是不上传保存到应用服务器,解析时无法解析到
XlsFile.SaveAs(file);
string strline;
string[] Ary;
bool Flag=true;
int intColCount = 0;
DataColumn dc;
DataRow dr;
DataTable dt = new DataTable();
//解析文件
StreamReader mysr = new StreamReader(file, System.Text.Encoding.Default);
//循环获取行数据 把行数据填充到一个DataRow中 然后转存到DataTable 最终效果就是把Data
while ((strline = mysr.ReadLine()) != null)
{
Ary = strline.Split(new char[] { ',' });
if (Flag)
{
Flag = false;
intColCount = Ary.Length;
int col = 0;
for (int i = 0; i < Ary.Length; i++)
{
col = i + 1;
dc = new DataColumn(col.ToString());
dt.Columns.Add(dc);
}
}
//填充数据并加入到datatable中
dr = dt.NewRow();
for (int i = 0; i < intColCount; i++)
{
string Value=Ary[i];
dr[i] = Value;
}
dt.Rows.Add(dr);
}
//可以对dataTable列名称进行转换
for (int i = 0; i < dt.Columns.Count; i++)
{
string ColName = Convert.ToString(dt.Columns[i].ColumnName);
if (BaiDu.ContainsKey(ColName))
{
dt.Columns[i].ColumnName = BaiDu[ColName];
}
}
#endregion
res.Bz = 1;
}
catch
{
res.Bz = 0;
res.Err = "文件上传过程失败,请重新上传验证!";
}
}
}
}
context.Response.Write(JsonConvert.SerializeObject(res));
}
4.class类直接转换为JSON返回到前台
JsonConvert.SerializeObject(res)