【发布时间】:2011-11-09 06:44:30
【问题描述】:
我编写了这个函数,它将所有管道转换为逗号,然后将其转换为 excel .CSV 文件。
但是,在那之后,我意识到某些行存在一些问题。
例如名字[Chua Wei Loon](应该在一列),最后“Chua Wei”在一列,“Loon”在下一列。
我查看了文本文件,发现名称之间没有管道,我找不到解决方案。
下面是我的函数代码:
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 文件的示例输出(突出显示有错误的行):
我意识到我的错误,这是由于变量中的命令导致名称拆分。
有什么建议可以让我仍然可以将它们转换为 .csv 文件,尽管变量之间有逗号?
【问题讨论】:
-
我的猜测是“Chua Wei | Loon”所在的那一行原本是“Chua Wei, Loon”当你把所有的管道转换成逗号时,你没有考虑到可能有逗号列中的数据(因此为什么它们以管道分隔开头?)您可能需要在管道所在的位置添加双引号,以便您得到“Chua Wei,Loon”,“普通用户”等。
-
你能告诉我们实际创建的文本数据吗?它只是一个实际文本的 .xls 文件,直到 excel 打开它并重新保存它。直接用记事本或者vs.net打开,看看数据是什么。调试起来似乎很简单。
-
双引号管道在哪里?这意味着我将不得不更改 fileContent = fileContent.Replace('|', ','); to fileContent = fileContent.Replace("|", ','); ?
-
我已经意识到我的错误,这是由于名称变量之间有逗号。有什么办法可以将 ',' 更改为而不是使用逗号进行转换?
-
不太……更像是替换“|”用 "\",\""
标签: c# asp.net visual-studio excel visual-studio-2005