读写csv文件
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Data;
using System.Text.RegularExpressions; using System.Diagnostics;
namespace CsvLib
{
#region Àà˵Ã?ÐÅÏ?
///
///
///
- ?ÁCSVÎÄ?þÀà,?ÁÈ?Ö???µÄCSVÎÄ?þ???ÉÒÔµ??öDataTable
/// -
///
///
///
/// yangzhihong
/// 2006/01/16
///
/// 1.0
///
#endregion
public class CsvStreamReader
{
private ArrayList rowAL; //ÐÐÁ??í,CSVÎÄ?þµÄÃ?Ò?ÐÐ?ÍÊÇÒ??öÁ?
private string fileName; //ÎÄ?þÃû
private Encoding encoding; //?àÂë
public CsvStreamReader()
{
this.rowAL = new ArrayList();
this.fileName = "";
this.encoding = Encoding.Default;
}
///
///
///
///
ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
public CsvStreamReader(string fileName)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = Encoding.Default;
LoadCsvFile();
}
///
///
///
///
ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
///
ÎÄ?þ?àÂë
public CsvStreamReader(string fileName,Encoding encoding)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = encoding;
LoadCsvFile();
}
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
///
public string FileName
{
set
{
this.fileName = value;
LoadCsvFile();
}
}
///
/// ÎÄ?þ?àÂë
///
public Encoding FileEncoding
{
set
{
this.encoding = value;
}
}
///
/// ?ñÈ?ÐÐÊý
///
public int RowCount
{
get
{
return this.rowAL.Count;
}
}
///
/// ?ñÈ?ÁÐÊý
///
public int ColCount
{
get
{
int maxCol;
maxCol = 0;
for (int i = 0;i
colAL.Count)?maxCol:colAL.Count;
}
return maxCol;
}
}
///
/// ?ñÈ?Ä?ÐÐÄ?ÁеÄÊý?Ý
/// row:ÐÐ,row = 1?ú?íµÚÒ?ÐÐ
/// col:ÁÐ,col = 1?ú?íµÚÒ?ÁÐ
///
public string this[int row,int col]
{
get
{
//Êý?ÝÓÐÐ?ÐÔÑéÖ?
CheckRowValid(row);
CheckColValid(col);
ArrayList colAL = (ArrayList) this.rowAL[row-1];
//Èç?ûÇëÇóÁÐÊý?Ý?óÓÚµ?Ç?ÐеÄÁÐÊ?,?µ?Ø?ÕÖµ
if (colAL.Count < col)
{
return "";
}
return colAL[col-1].ToString();
}
}
///
///
?ù?Ý×îÐ?ÐÐ??×î?óÐÐ??×îÐ?ÁÐ??×î?óÁÐ??À?Éú?ÉÒ??öDataTableÀàÐ͵ÄÊý?Ý
/// ÐеÈÓÚ1?ú?íµÚÒ?ÐÐ
/// ÁеÈÓÚ1?ú?íµÚÒ?ÁÐ
/// maxrow: -1?ú?í×î?óÐÐ
/// maxcol: -1?ú?í×î?óÁÐ
///
public DataTable this[int minRow,int maxRow,int minCol,int maxCol]
{
get
{
//Êý?ÝÓÐÐ?ÐÔÑéÖ?
CheckRowValid(minRow);
CheckMaxRowValid(maxRow);
CheckColValid(minCol);
CheckMaxColValid(maxCol);
if (maxRow == -1)
{
maxRow = RowCount;
}
if (maxCol == -1)
{
maxCol = ColCount;
}
if (maxRow < minRow)
{
throw new Exception("×î?óÐÐÊý??ÄÜÐ?ÓÚ×îÐ?ÐÐÊý");
}
if (maxCol < minCol)
{
throw new Exception("×î?óÁÐÊý??ÄÜÐ?ÓÚ×îÐ?ÁÐÊý");
}
DataTable csvDT = new DataTable();
int i;
int col;
int row;
//Ôö?ÓÁÐ
for (i = minCol;i <= maxCol;i++)
{
csvDT.Columns.Add(i.ToString());
}
for (row = minRow;row <= maxRow;row++)
{
DataRow csvDR = csvDT.NewRow();
i = 0;
for (col = minCol;col <=maxCol;col++)
{
csvDR[i] = this[row,col];
i++;
}
csvDT.Rows.Add(csvDR);
}
return csvDT;
}
}
///
/// ?ì?éÐÐÊýÊÇ?ñÊÇÓÐÐ?µÄ
///
///
private void CheckRowValid(int row)
{
if (row <= 0)
{
throw new Exception("ÐÐÊý??ÄÜÐ?ÓÚ0");
}
if (row > RowCount)
{
throw new Exception("Ã?Óе?Ç?ÐеÄÊý?Ý");
}
}
///
/// ?ì?é×î?óÐÐÊýÊÇ?ñÊÇÓÐÐ?µÄ
///
///
private void CheckMaxRowValid(int maxRow)
{
if (maxRow <= 0 && maxRow != -1)
{
throw new Exception("ÐÐÊý??ÄܵÈÓÚ0?òÐ?ÓÚ-1");
}
if (maxRow > RowCount)
{
throw new Exception("Ã?Óе?Ç?ÐеÄÊý?Ý");
}
}
///
/// ?ì?éÁÐÊýÊÇ?ñÊÇÓÐÐ?µÄ
///
///
private void CheckColValid(int col)
{
if (col <= 0)
{
throw new Exception("ÁÐÊý??ÄÜÐ?ÓÚ0");
}
if (col > ColCount)
{
throw new Exception("Ã?Óе?Ç?ÁеÄÊý?Ý");
}
}
///
/// ?ì?é?ì?é×î?óÁÐÊýÊÇ?ñÊÇÓÐÐ?µÄ
///
///
private void CheckMaxColValid(int maxCol)
{
if (maxCol <= 0 && maxCol != -1)
{
throw new Exception("ÁÐÊý??ÄܵÈÓÚ0?òÐ?ÓÚ-1");
}
if (maxCol > ColCount)
{
throw new Exception("Ã?Óе?Ç?ÁеÄÊý?Ý");
}
}
///
/// ÔØÈëCSVÎÄ?þ
///
private void LoadCsvFile()
{
//?ÔÊý?ݵÄÓÐÐ?ÐÔ?øÐÐÑéÖ?
if (this.fileName == null)
{
throw new Exception("ÇëÖ???ÒªÔØÈëµÄCSVÎÄ?þÃû");
}
else if (!File.Exists(this.fileName))
{
throw new Exception("Ö???µÄCSVÎÄ?þ???æÔÚ");
}
else
{
}
if (this.encoding == null)
{
this.encoding = Encoding.Default;
}
StreamReader sr = new StreamReader(this.fileName,this.encoding);
string csvDataLine;
csvDataLine = "";
while (true)
{
string fileDataLine;
fileDataLine = sr.ReadLine();
if (fileDataLine == null)
{
break;
}
if (csvDataLine == "")
{
csvDataLine =
fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
}
else
{
csvDataLine += "/r/n" +
fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
}
//Èç?û?üº?Å?Êý?öÒýºÅ??˵Ã??ÃÐÐÊý?ÝÖÐ?öÏÖ?Ø?µ?û?ò?üº??ººÅ
if (!IfOddQuota(csvDataLine))
{
AddNewDataLine(csvDataLine);
csvDataLine = "";
}
}
sr.Close();
//Êý?ÝÐÐ?öÏÖÆæÊý?öÒýºÅ
if (csvDataLine.Length > 0)
{
throw new Exception("CSVÎÄ?þµÄ?ñÊ?ÓÐ?íÎó");
}
}
///
/// ?ñÈ?Á??öÁ?ÐøÒýºÅ?ä?ɵ??öÒýºÅµÄÊý?ÝÐÐ
///
/// ÎÄ?þÊý?ÝÐÐ
///
private string GetDeleteQuotaDataLine(string fileDataLine)
{
return fileDataLine.Replace("/"/"","/"");
}
///
/// ÅÐ?Ï×Ö?û??ÊÇ?ñ?üº?ÆæÊý?öÒýºÅ
///
/// Êý?ÝÐÐ
/// ΪÆæÊýÊ????µ?ØΪÕæ???ñÔò?µ?ØΪ?Ù
private bool IfOddQuota(string dataLine)
{
int quotaCount;
bool oddQuota;
quotaCount = 0;
for (int i = 0;i < dataLine.Length;i++)
{
if (dataLine[i] == '/"')
{
quotaCount++;
}
}
oddQuota = false;
if (quotaCount % 2 == 1)
{
oddQuota = true;
}
return oddQuota;
}
///
/// ÅÐ?ÏÊÇ?ñÒÔÆæÊý?öÒýºÅ?ªÊ?
///
///
///
private bool IfOddStartQuota(string dataCell)
{
int quotaCount;
bool oddQuota;
quotaCount = 0;
for (int i = 0;i < dataCell.Length;i++)
{
if (dataCell[i] == '/"')
{
quotaCount++;
}
else
{
break;
}
}
oddQuota = false;
if (quotaCount % 2 == 1)
{
oddQuota = true;
}
return oddQuota;
}
///
/// ÅÐ?ÏÊÇ?ñÒÔÆæÊý?öÒýºÅ?áÎ?
///
///
///
private bool IfOddEndQuota(string dataCell)
{
int quotaCount;
bool oddQuota;
quotaCount = 0;
for (int i = dataCell.Length -1;i >= 0;i--)
{
if (dataCell[i] == '/"')
{
quotaCount++;
}
else
{
break;
}
}
oddQuota = false;
if (quotaCount % 2 == 1)
{
oddQuota = true;
}
return oddQuota;
}
///
/// ?ÓÈëеÄÊý?ÝÐÐ
///
/// еÄÊý?ÝÐÐ
private void AddNewDataLine(string newDataLine)
{
Debug.WriteLine("NewLine:" + newDataLine);
//return;
ArrayList colAL = new ArrayList();
string[] dataArray = newDataLine.Split(',');
bool oddStartQuota; //ÊÇ?ñÒÔÆæÊý?öÒýºÅ?ªÊ?
string cellData;
oddStartQuota = false;
cellData = "";
for (int i = 0 ;i < dataArray.Length;i++)
{
if (oddStartQuota)
{
//ÒòΪÇ?ÃæÓÃ?ººÅ?Ö?î,ËùÒÔÒª?ÓÉÏ?ººÅ
cellData += "," + dataArray[i];
//ÊÇ?ñÒÔÆæÊý?öÒýºÅ?áÎ?
if (IfOddEndQuota(dataArray[i]))
{
colAL.Add(GetHandleData(cellData));
oddStartQuota = false;
continue;
}
}
else
{
//ÊÇ?ñÒÔÆæÊý?öÒýºÅ?ªÊ?
if (IfOddStartQuota(dataArray[i]))
{
//ÊÇ?ñÒÔÆæÊý?öÒýºÅ?áÎ?,??ÄÜÊÇÒ??öË?ÒýºÅ,??ÇÒ??ÊÇÆæÊý?öÒýºÅ
if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2
&& !IfOddQuota(dataArray[i]))
{
colAL.Add(GetHandleData(dataArray[i]));
oddStartQuota = false;
continue;
}
else
{
oddStartQuota = true;
cellData = dataArray[i];
continue;
}
}
else
{
colAL.Add(GetHandleData(dataArray[i]));
}
}
}
if (oddStartQuota)
{
throw new Exception("Êý?Ý?ñÊ?ÓÐÎÊÌâ");
}
this.rowAL.Add(colAL);
}
///
/// È?µô?ñ×ÓµÄÊ×Î?ÒýºÅ???ÑË?ÒýºÅ?ä?ɵ?ÒýºÅ
///
///
///
private string GetHandleData(string fileCellData)
{
if (fileCellData == "")
{
return "";
}
if (IfOddStartQuota(fileCellData))
{
if (IfOddEndQuota(fileCellData))
{
return
fileCellData.Substring(1,fileCellData.Length-2).Replace("/"/"","/"
"); //È?µôÊ×Î?ÒýºÅ??È?ºó?ÑË?ÒýºÅ?ä?ɵ?ÒýºÅ
}
else
{
throw new Exception("Êý?ÝÒýºÅÎÞ??Æ?Åä" + fileCellData);
}
}
else
{
//??ÂÇÐÎÈç"" """" """"""
if (fileCellData.Length >2 && fileCellData[0] == '/"')
{
fileCellData =
fileCellData.Substring(1,fileCellData.Length-2).Replace("/"/"","/"
"); //È?µôÊ×Î?ÒýºÅ??È?ºó?ÑË?ÒýºÅ?ä?ɵ?ÒýºÅ
}
}
return fileCellData;
}
}
}
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Data;
namespace CsvLib
{
#region Àà˵Ã?ÐÅÏ?
///
///
///
- Ð?CSVÎÄ?þÀà,Ê×ÏÈ?øCSVÎÄ?þ??Öµ,×îºóÍ??ýSave?????øÐÐ???æ?Ù×?<
/b>
/// -
///
///
///
/// yangzhihong
/// 2006/01/16
///
/// 1.0
///
#endregion
public class CsvStreamWriter
{
private ArrayList rowAL; //ÐÐÁ??í,CSVÎÄ?þµÄÃ?Ò?ÐÐ?ÍÊÇÒ??öÁ?
private string fileName; //ÎÄ?þÃû
private Encoding encoding; //?àÂë
public CsvStreamWriter()
{
this.rowAL = new ArrayList();
this.fileName = "";
this.encoding = Encoding.Default;
}
///
///
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
public CsvStreamWriter(string fileName)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = Encoding.Default;
}
///
///
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
/// ÎÄ?þ?àÂë
public CsvStreamWriter(string fileName,Encoding encoding)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = encoding;
}
///
/// row:ÐÐ,row = 1?ú?íµÚÒ?ÐÐ
/// col:ÁÐ,col = 1?ú?íµÚÒ?ÁÐ
///
public string this[int row,int col]
{
set
{
//?ÔÐÐ?øÐÐÅÐ?Ï
if (row <= 0)
{
throw new Exception("ÐÐÊý??ÄÜÐ?ÓÚ0");
}
else if (row > this.rowAL.Count) //Èç?ûµ?Ç?ÁÐÁ?µÄÐÐÊý??????Òª??Æë
{
for (int i = this.rowAL.Count + 1;i <= row;i++)
{
this.rowAL.Add(new ArrayList());
}
}
else
{
}
//?ÔÁÐ?øÐÐÅÐ?Ï
if (col <= 0)
{
throw new Exception("ÁÐÊý??ÄÜÐ?ÓÚ0");
}
else
{
ArrayList colTempAL = (ArrayList) this.rowAL[row-1];
//À??ó???È
if (col > colTempAL.Count)
{
for (int i = colTempAL.Count;i <= col;i++)
{
colTempAL.Add("");
}
}
this.rowAL[row-1] = colTempAL;
}
//??Öµ
ArrayList colAL = (ArrayList) this.rowAL[row-1];
colAL[col-1] = value;
this.rowAL[row-1] = colAL;
}
}
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
///
public string FileName
{
set
{
this.fileName = value;
}
}
///
/// ÎÄ?þ?àÂë
///
public Encoding FileEncoding
{
set
{
this.encoding = value;
}
}
///
/// ?ñÈ?µ?Ç?×î?óÐÐ
///
public int CurMaxRow
{
get
{
return this.rowAL.Count;
}
}
///
/// ?ñÈ?×î?óÁÐ
///
public int CurMaxCol
{
get
{
int maxCol;
maxCol = 0;
for (int i = 0;i colAL.Count)?maxCol:colAL.Count;
}
return maxCol;
}
}
///
/// Ìí?Ó?íÊý?ݵ?CSVÎÄ?þÖÐ
///
/// ?íÊý?Ý
/// ?ÓµÚ??ÁÐ?ªÊ?,beginCol =
1?ú?íµÚÒ?ÁÐ
public void AddData(DataTable dataDT,int beginCol)
{
if (dataDT == null)
{
throw new Exception("ÐèÒªÌí?ÓµÄ?íÊý?ÝΪ?Õ");
}
int curMaxRow;
curMaxRow = this.rowAL.Count;
for (int i = 0;i < dataDT.Rows.Count;i++)
{
for (int j = 0;j
/// ???æÊý?Ý,Èç?ûµ?Ç?Ó?ÅÌÖÐÒÑ?,?æÔÚÎÄ?þÃûÒ?ÑùµÄÎÄ?þ?????á???Ç
///
public void Save()
{
//?ÔÊý?ݵÄÓÐÐ?ÐÔ?øÐÐÅÐ?Ï
if (this.fileName == null)
{
throw new Exception("È?ÉÙÎÄ?þÃû");
}
else if (File.Exists(this.fileName))
{
File.Delete(this.fileName);
}
if (this.encoding == null)
{
this.encoding = Encoding.Default;
}
System.IO.StreamWriter sw = new
StreamWriter(this.fileName,false,this.encoding);
for (int i = 0 ;i < this.rowAL.Count;i++)
{
sw.WriteLine(ConvertToSaveLine((ArrayList) this.rowAL[i]));
}
sw.Close();
}
///
/// ???æÊý?Ý,Èç?ûµ?Ç?Ó?ÅÌÖÐÒÑ?,?æÔÚÎÄ?þÃûÒ?ÑùµÄÎÄ?þ?????á???Ç
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
public void Save(string fileName)
{
this.fileName = fileName;
Save();
}
///
/// ???æÊý?Ý,Èç?ûµ?Ç?Ó?ÅÌÖÐÒÑ?,?æÔÚÎÄ?þÃûÒ?ÑùµÄÎÄ?þ?????á???Ç
///
/// ÎÄ?þÃû,?üÀ?ÎÄ?þÂ???
/// ÎÄ?þ?àÂë
public void Save(string fileName,Encoding encoding)
{
this.fileName = fileName;
this.encoding = encoding;
Save();
}
///
/// ת???É???æÐÐ
///
/// Ò?ÐÐ
///
private string ConvertToSaveLine(ArrayList colAL)
{
string saveLine;
saveLine = "";
for (int i = 0;i< colAL.Count;i++)
{
saveLine += ConvertToSaveCell(colAL[i].ToString());
//?ñ×Ó?äÒÔ?ººÅ?Ö?î
if (i < colAL.Count - 1)
{
saveLine += ",";
}
}
return saveLine;
}
///
/// ×Ö?û??ת???ÉCSVÖеÄ?ñ×Ó
/// Ë?ÒýºÅת???ÉÁ??öË?ÒýºÅ??È?ºóÊ×Î????ÓÒ??öË?ÒýºÅ
/// ÕâÑù?Í??ÐèÒª??ÂÇ?ººÅ????ÐеÄÎÊÌâ
///
/// ?ñ×ÓÄÚÈÝ
///
private string ConvertToSaveCell(string cell)
{
cell = cell.Replace("/"","/"/"");
return "/"" + cell + "/"";
}
}
}