1

I am using VS2005 C# and im trying to convert a pipe delimited text file to excel workbook format. Below is my code:

public partial class TextToExcel : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SaveAsExcelBtn_Click(object sender, EventArgs e)
    {

        string xlExtension = ".csv";
        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('Failed to import. Cause: 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;

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


            //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('Failed to import. Cause: No file found');</script>");
    }
}

Currently I am having some file saving errors

Any suggestions? Thanks a lot!

enter image description here

gymcode
  • 4,431
  • 15
  • 72
  • 128

3 Answers3

1

That's because Excel doesnt support pipelines you have to convert it so comma's or semicolumns like:

using (StreamWriter outputWriter = new StreamWriter(File.Create(strExcelOutputFilename)))
{
    StreamReader inputReader = new StreamReader(TextFile.FileContent);
    string fileContent = inputReader.ReadToEnd();

    fileContent = fileContent.Replace('|', ',');
    outputWriter.Write(fileContent);
}
Polity
  • 14,734
  • 2
  • 40
  • 40
  • After i change pipelines to comma's, i can use the output too convert to .xls straight? how do i save the output file of this? – gymcode Nov 08 '11 at 03:34
  • In my code example, i both convert pipes to semicolumns and i save it to the output file. Note these lines: new StreamWriter(File.Create(strExcelOutputFilename)) and outputWriter.Write(fileContent); – Polity Nov 08 '11 at 03:37
  • I put ur code my my method, but it says that system.web.ui.webcontrols.fileupload does not contain a definition for inputstream. I do not know where else i can put ur code as the strExcelOutputFile perimeter can only be retrieved in my upload method – gymcode Nov 08 '11 at 03:50
  • @RUiHAO - Updated my code to use FileContent rather than InputStream, now it should work – Polity Nov 08 '11 at 03:52
  • I have updated my code to include your streamwriter, and I can see that the fileContent is in commas instead of pipes. However what is the next step I should to to convert to excel file arrange by columns? I have tried changing the file extension-only but it still does not work. Thank you – gymcode Nov 08 '11 at 04:05
  • @RUiHAO - change the file's extension to CSV will be all – Polity Nov 08 '11 at 04:06
  • TextFile.SaveAs(strExcelOutputFilename)? Do I need to change the TextFile to something else? For now I'm having an error that says the file is used by another program and can't be saved. I have updated my latest code and additional screenshots. Thanks alot – gymcode Nov 08 '11 at 05:32
  • @RUiHAO - TextFile.SaveAs becomes obsolete because outputWriter.Write already saves the content. you can remove that line – Polity Nov 08 '11 at 05:38
  • I have managed to save the file as a .csv. However the content in the excel file is still not in column. I've attached a screenshot above. Thanks – gymcode Nov 08 '11 at 05:47
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4793/discussion-between-polity-and-ruihao) – Polity Nov 08 '11 at 05:52
  • @RUiHAO - I see, i'm sorry, you can easily fix this by replacing ';' with ','. It depends on a setting in windows/excel whether it expects ';' by default. I'll update the sample – Polity Nov 08 '11 at 05:53
  • Hi Polity, it worked! I can now save as a .CSV file. However, is there any way to convert .CSV file to .XLS? Because I have an import function which gave me an error that says external table is not in the expected format, although the tables are the same as the one I have in .xls version. – gymcode Nov 08 '11 at 07:14
  • is it possible to replace the ',' with other variables so that it is able to save as an excel workbook? – gymcode Nov 08 '11 at 07:33
  • @RUiHAO - Ofcourse, you can extend it as much as you want. Just keep in mind that excel only interprets CSV files using a limited number of ways. – Polity Nov 08 '11 at 07:36
  • Do you know what variable I can change to make it save as a .XLS file? Because I'm having some errors after the conversion, some rows are messed up and I have no idea why. http://stackoverflow.com/questions/8061307/rows-messed-up-when-converting-pipe-delimited-text-files-to-csv-excel-file-c-sh This is the error I met, can you take a look for me? Thanks alot – gymcode Nov 09 '11 at 06:54
0

I googled and hope it will help you: http://csharp.net-informations.com/excel/csharp-create-excel.htm

Or, already answered: Create Excel (.XLS and .XLSX) file from C#

At the first link, the line xlWorkSheet.Cell[x,y] to put element in the dedicated cell.

FYI, xlsx format(new from Office 2007) will give you a great manipulation capability with code.

Community
  • 1
  • 1
Youngjae
  • 24,352
  • 18
  • 113
  • 198
0

For generating and manipulating excel files, I personally prefer the NPOI library. Download it from Codeplex, add reference to the NPOI dlls to your project. Store a “template” excel file you would like in a known location, with the any column headers/formatting that you need. Then you just use npoi to make a copy of the template file and manipulate it at a sheet/row/column level and put whatever data you want.

The sample code snippet looks something like this. Assuming you have split your input into a List of strings

const string ExcelTemplateFile = "~/Resources/ExcelInputTemplate.xls";
const string ExcelWorksheetName = "Output Worksheet";
const int RequiredColumn = 1;

private HSSFWorkbook CreateExcelWorkbook(IEnumerable<String> inputData)
{
        FileStream fs = new FileStream(Server.MapPath(ExcelTemplateFile), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet(ExcelWorksheetName);

        int startRowIterator = 1;

        foreach (string currentData in inputData)
        {
            sheet.CreateRow(startRowIterator).CreateCell(RequiredColumn).SetCellValue(currentData);
        }
}
Chaitanya
  • 5,203
  • 8
  • 36
  • 61