ASP .Net C# ---CSV导入导出
csv和excel大致相同 复制下来 数据传到方法里面就可以了
/// <summary>
/// datatable数据写入csv文件
/// </summary>
/// <param name="dt"></param>
/// <param name="fullpath"></param>
public void savecsv(datatable dt, string fullpath)//table数据写入csv
{
system.io.fileinfo fi = new system.io.fileinfo(fullpath);
if (!fi.directory.exists)
{
fi.directory.create();
}
system.io.filestream fs = new system.io.filestream(fullpath, system.io.filemode.create,
system.io.fileaccess.write);
system.io.streamwriter sw = new system.io.streamwriter(fs, system.text.encoding.utf8);
string data = "";
for (int i = 0; i < dt.columns.count; i++)//写入列名
{
data += dt.columns[i].columnname.tostring();
if (i < dt.columns.count - 1)
{
data += ",";
}
}
sw.writeline(data);
for (int i = 0; i < dt.rows.count; i++) //写入各行数据
{
data = "";
for (int j = 0; j < dt.columns.count; j++)
{
string str = dt.rows[i][j].tostring();
str = str.replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.contains(',') || str.contains('"')
|| str.contains('\r') || str.contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.format("\"{0}\"", str);
}
data += str;
if (j < dt.columns.count - 1)
{
data += ",";
}
}
sw.writeline(data);
}
sw.close();
fs.close();
}
/// <summary>
/// 读取csv文件到datatable
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public datatable opencsv(string filepath)//从csv读取数据返回table
{
system.text.encoding encoding = gettype(filepath); //encoding.ascii;//
datatable dt = new datatable();
system.io.filestream fs = new system.io.filestream(filepath, system.io.filemode.open,
system.io.fileaccess.read);
system.io.streamreader sr = new system.io.streamreader(fs, encoding);
//记录每次读取的一行记录
string strline = "";
//记录每行记录中的各字段内容
string[] aryline = null;
string[] tablehead = null;
//标示列数
int columncount = 0;
//标示是否是读取的第一行
bool isfirst = true;
//逐行读取csv中的数据
while ((strline = sr.readline()) != null)
{
if (isfirst == true)
{
tablehead = strline.split(',');
isfirst = false;
columncount = tablehead.length;
//创建列
for (int i = 0; i < columncount; i++)
{
datacolumn dc = new datacolumn(tablehead[i]);
dt.columns.add(dc);
}
}
else
{
aryline = strline.split(',');
datarow dr = dt.newrow();
for (int j = 0; j < columncount; j++)
{
dr[j] = aryline[j];
}
dt.rows.add(dr);
}
}
if (aryline != null && aryline.length > 0)
{
dt.defaultview.sort = tablehead[0] + " " + "asc";
}
sr.close();
fs.close();
return dt;
}
/// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型
/// <param name="file_name">文件路径</param>
/// <returns>文件的编码类型</returns>
public static system.text.encoding gettype(string file_name)
{
system.io.filestream fs = new system.io.filestream(file_name, system.io.filemode.open,
system.io.fileaccess.read);
system.text.encoding r = gettype(fs);
fs.close();
return r;
}
/// 通过给定的文件流,判断文件的编码类型
/// <param name="fs">文件流</param>
/// <returns>文件的编码类型</returns>
public static system.text.encoding gettype(system.io.filestream fs)
{
byte[] unicode = new byte[] { 0xff, 0xfe, 0x41 };
byte[] unicodebig = new byte[] { 0xfe, 0xff, 0x00 };
byte[] utf8 = new byte[] { 0xef, 0xbb, 0xbf }; //带bom
system.text.encoding reval = system.text.encoding.default;
system.io.binaryreader r = new system.io.binaryreader(fs, system.text.encoding.default);
int i;
int.tryparse(fs.length.tostring(), out i);
byte[] ss = r.readbytes(i);
if (isutf8bytes(ss) || (ss[0] == 0xef && ss[1] == 0xbb && ss[2] == 0xbf))
{
reval = system.text.encoding.utf8;
}
else if (ss[0] == 0xfe && ss[1] == 0xff && ss[2] == 0x00)
{
reval = system.text.encoding.bigendianunicode;
}
else if (ss[0] == 0xff && ss[1] == 0xfe && ss[2] == 0x41)
{
reval = system.text.encoding.unicode;
}
r.close();
return reval;
}
/// 判断是否是不带 bom 的 utf8 格式
/// <param name="data"></param>
/// <returns></returns>
private static bool isutf8bytes(byte[] data)
{
int charbytecounter = 1; //计算当前正分析的字符应还有的字节数
byte curbyte; //当前分析的字节.
for (int i = 0; i < data.length; i++)
{
curbyte = data[i];
if (charbytecounter == 1)
{
if (curbyte >= 0x80)
{
//判断当前
while (((curbyte <<= 1) & 0x80) != 0)
{
charbytecounter++;
}
//标记位首位若为非0 则至少以2个1开始 如:110xxxxx...........1111110x
if (charbytecounter == 1 || charbytecounter > 6)
{
return false;
}
}
}
else
{
//若是utf-8 此时第一位必须为1
if ((curbyte & 0xc0) != 0x80)
{
return false;
}
charbytecounter--;
}
}
if (charbytecounter > 1)
{
throw new exception("非预期的byte格式");
}
return true;
}
/// <summary>
/// 修改文件名称
/// 我们需要保存历史数据 或者实时的知道那个文件被修改 可以通过改变文件的名称 如加上当天的日期等等。
/// </summary>
/// <param name="oldpath"></param>
/// <param name="newpath"></param>
/// <returns></returns>
public static bool changefilename(string oldpath, string newpath)
{
bool re = false;
try
{
if (file.exists(oldpath))
{
file.move(oldpath, newpath);
re = true;
}
}
catch
{
re = false;
}
return re;
}
/// <summary>
/// csv文件的数据写入
/// 直接在网页表单提交数据保存在csv文件中 直接写入文件
/// </summary>
/// <param name="fullpath"></param>
/// <param name="data"></param>
/// <returns></returns>
public static bool savecsv(string fullpath, string data)
{
bool re = true;
try
{
filestream filestream = new filestream(fullpath, filemode.append);
streamwriter sw = new streamwriter(filestream, system.text.encoding.utf8);
sw.writeline(data);
//清空缓冲区
sw.flush();
//关闭流
sw.close();
filestream.close();
}
catch
{
re = false;
}
return re;
}
上一篇: net 把指定 URI 的资源下载到本地
下一篇: 微信小程序登录按钮遮罩浮层效果的实现方法