2011-11-09 39 views
0

我正在使用VS2005 C#,我试图将一个excel文件导入SQL Server数据库。从管道分隔的文本文件传输到.CSV后Excel行弄乱了

目前我正试图直接将管道分隔的文本文件转换为.XLS格式。

但是我找不到办法做到这一点,所以我试图将管道分隔的文本文件转换为.CSV。

但最后,转换完成后,我意识到在一些变量之间有一些默认的comman,导致行被搞乱。

有谁知道无论如何忽略变量中的默认commans,或使用其他变量而不是commans?下面是我的转换函数的代码:

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; 
      } 

      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:/"; 
       } 

      } 
     } 
     else Response.Write("<script>alert('Please select a file');</script>"); 
    } 

谢谢

回答

1

你需要处理的行的文件行 - 尝试

while (inputReader.Peek() >= 0) 
{ 
string[] myInputFields = inputReader.ReadLine().Split (new char[] { '|' }); 
List<string> myOutputFields = new List<string>(); 

foreach (string aField in myInputFields) 
{ 
    string oField = aField; 
    if (oField.Contains (",")) 
      oField = "\"" + oField + "\""; 

    myOutputFields.Add (oField); 
} 

outputWriter.WriteLine (string.Join (",", myOutputFields.ToArray())); 
}; 

这需要一个行输入文件和分裂它找到每个管道|的“字段”,然后它建立一个新的行作为分隔符,,并在此过程中包含任何已包含,和双引号"的字段...

MSDN引用:

编辑 - 按评论:

上面的代码替换从原始代码中的以下3行:

string fileContent = inputReader.ReadToEnd(); 
fileContent = fileContent.Replace('|', ','); 
outputWriter.Write(fileContent); 
+0

您好亚希阿,所以我会尝试更换我的代码 outputWriter.Write(fileContent); 与您的代码? – gymcode

+0

@RUHAHAO no ...它取代了上面的两行...请看我上面的编辑... – Yahia

+0

谢谢Yahia!有效!现在我的代码不会受到指挥官的干扰。现在我没有看到我新创建的Excel表中有任何逗号。我可以知道你的代码是如何工作的吗?只是一个简单的解释会为我做。非常感谢! – gymcode

相关问题