I am using VS2005 C#, I am trying to import an excel filesheet into SQL server database.
Currently I am trying to convert pipe-delimited text files into .XLS format directly.
However I could not find a way to do it, so I tried to convert pipe-delimited text files to .CSV instead.
But in the end, after the conversion was done, I realize that there are some default commans in between some variables, causing the rows to be messed up.
Does anyone know anyway to ignore the default commans in the variables, or using another variable instead of commans? Below is the code for my conversion function:
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>");
}
Thank you
you need to process the file line by line – try
This takes a line from the input file and split it into “fields” at every pipe
|it finds… then it builds a new line with,as a delimiter and enclosing any field which already contains,with double quotes"in the process…MSDN references:
EDIT – as per comment:
The above code replaces the following 3 lines from the original code: