C#VS2005将管道分隔.TXT转换为Excel工作簿.XLS

时间:2011-11-08 02:54:31

标签: c# visual-studio excel visual-studio-2005

我正在使用VS2005 C#,我试图将管道分隔的文本文件转换为excel工作簿格式。以下是我的代码:

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

目前我有一些文件保存错误

有什么建议吗?非常感谢!

enter image description here

3 个答案:

答案 0 :(得分:1)

那是因为Excel不支持管道,你必须将其转换为逗号或半字节,如:

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

    fileContent = fileContent.Replace('|', ',');
    outputWriter.Write(fileContent);
}

答案 1 :(得分:0)

我用Google搜索并希望它会对您有所帮助:http://csharp.net-informations.com/excel/csharp-create-excel.htm

或者,已经回答:Create Excel (.XLS and .XLSX) file from C#

在第一个链接处, xlWorkSheet.Cell [x,y] 行将元素放入专用单元格中。

仅供参考,xlsx格式(来自Office 2007的新版本)将为您提供强大的代码操作功能。

答案 2 :(得分:0)

为了生成和操作excel文件,我个人更喜欢NPOI库。从Codeplex下载它,向您的项目添加对NPOI dll的引用。将您想要的“模板”Excel文件存储在已知位置,并使用您需要的任何列标题/格式。然后你只需使用npoi制作模板文件的副本并在工作表/行/列级别操作它并放入你想要的任何数据。

示例代码段看起来像这样。假设您已将输入拆分为字符串列表

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);
        }
}
相关问题