public class CSVHelper
{
/// <summary>
/// 专利导出
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="directory"></param>
/// <param name="objs"></param>
/// <returns></returns>
public static string CreateCSV(string directory, List<PatentInfo> objs, Dictionary<string, string> patentFields)
{
string outputString = "";
patentFields.Remove("SYSID");
foreach (string field in patentFields.Keys)
{
if (!string.IsNullOrEmpty(field))
{
string temp = field;
temp = temp.Replace("/"", "/"/"");
temp = "/"" + temp + "/",";
outputString += temp;
}
}
outputString += "/r/n";
for (int i = 0; i < objs.Count; i++)
{
for (int j = 0; j < patentFields.Count(); j++)
{
string temp = null;
try
{
temp = objs[i].Fields[patentFields.Values.ToList()[j]];
}
catch
{ temp = null; }
temp = temp == null ? "" : temp.Replace("<span class=/"highlightspan/">", "").Replace("</span>", "");
temp = temp.Replace("/"", "/"/"");
temp = "/"" + temp + "/",";
outputString += temp;
}
outputString += "/r/n";
}
outputString += "/r/n";
string path = directory;
if (!path.EndsWith("//")&&!path.EndsWith("/"))
{
path += "//";
}
string fileName = Math.Abs(DateTime.Now.GetHashCode()).ToString() + ".csv";
try
{
using (StreamWriter sw = new StreamWriter(path + fileName, false, Encoding.GetEncoding("gb2312")))
{
sw.Write(outputString);
}
}
catch
{
string[] pathsStr = GetFileNames(path, fileName.Substring(0, fileName.Length - 4)+"*");
if (pathsStr != null && pathsStr.Length > 0)
{
foreach (string pathX in pathsStr)
{
if (File.Exists(pathX))
{
File.Delete(pathX);
}
}
}
return null;
}
return fileName;
}
//返回指定目录下的文件名称
/// <summary>
///
/// </summary>
/// <param name="directoryPath">指定目录</param>
/// <param name="searchPattern">文件名称</param>
/// <returns></returns>
public static string[] GetFileNames(string directoryPath, string searchPattern)
{
//如果目录不存在,则抛出异常
if (!Directory.Exists(directoryPath))
{
throw new FileNotFoundException("当前路径不存在!");
}
try
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
}
catch
{
return null;
}
}
//删除文件
/// <summary>
///
/// </summary>
/// <param name="directoryPath">文件路径</param>
/// <returns></returns>
public static bool DeleteFile(string directoryPath)
{
try
{
//如果目录不存在,则抛出异常
if (!File.Exists(directoryPath))
{
throw new FileNotFoundException("当前路径不存在!");
}
File.Delete(directoryPath);
return true;
}
catch
{
return false;
}
}
}