我编写了将所有管道转换为逗号的函数,然后将其转换为excel .CSV文件。将管道分隔文本文件转换为.CSV excel文件时出现乱码
但是,在那之后,我意识到有些行有一些问题。
E.g.姓名[蔡伟龙](应该是在一列中),结果是“蔡伟”在一列中,“龙”在下一列。
我查看了文本文件,发现名称之间没有管道,我无法找到解决方案。
下面是我的功能代码:
protected void SaveAsExcelBtn_Click(object sender, EventArgs e)
{
//string strExcelOutputFilename = "C:/Documents and Settings/rhlim/My Documents/" + DateTime.Now.ToString("yyyyMMddHHmmss") + xlExtension;
// Before attempting to import the file, verify
// that the FileUpload control contains a file.
if (TextFile.HasFile)
{
// Get the name of the Excel spreadsheet.
string strFileName = Server.HtmlEncode(TextFile.FileName);
// Get the extension of the text.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".TXT" && strExtension!=".txt")
{
Response.Write("<script>alert('Invalid text file!');</script>");
return;
}
// Generate the file name to save the text file.
//string strUploadFileName = "C:/Documents and Settings/rhlim/My Documents/Visual Studio 2005/WebSites/SoD/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
if (DEMUserRoleRB.Checked)
{
string strExcelOutputFilename = "C:/" + "userrolelist" + xlExtension;
using (StreamWriter outputWriter = new StreamWriter(File.Create(strExcelOutputFilename)))
{
StreamReader inputReader = new StreamReader(TextFile.FileContent);
string fileContent = inputReader.ReadToEnd();
fileContent = fileContent.Replace('|', ',');
outputWriter.Write(fileContent);
//TextFile.SaveAs(strExcelOutputFilename);
inputReader.Close();
UploadStatusLabel.Text = "Conversion successful. File is stored at directory C:/";
}
//string strExcelOutputFilename = "C:/Documents and Settings/rhlim/My Documents/" + DateTime.Now.ToString("yyyyMMddHHmmss")+xlExtension;
// Save the Excel spreadsheet on server.
//TextFile.SaveAs (strExcelOutputFilename);
}
}
else Response.Write("<script>alert('Please select a file');</script>");
.csv文件的示例输出(有错误行高亮显示):
我已经意识到我的错误,这是由于在变量内部有commans导致名称分裂。
是否有任何建议,我仍然可以将它们转换为.csv文件,尽管变量之间有comman?
我的猜测是“Chua Wei | Loon”这一行最初是“Chua Wei,Loon”当您将所有管道转换为逗号时,您并没有考虑到列中的数据可能会有逗号(因此为什么它们是以管道分隔开始的?)您可能需要在管道的哪个位置添加双引号,以便获得“Chua Wei,Loon”,“Normal User”等。 –
您能向我们展示吗实际创建的文本数据?它只是一个.xls文件,它是实际的文本,直到excel打开并重新保存它。直接用记事本或vs.net打开它,看看数据是什么。似乎非常简单的调试。 –
双引号,其中管道是?这意味着我将不得不改变fileContent = fileContent.Replace('|',','); fileContent = fileContent.Replace(“|”,','); ? – gymcode