Windows窗体使用excel输入/保存到FilePath问题

时间:2017-06-08 13:10:21

标签: c# excel winforms

我有一个简单的窗体,输入了人员详细信息。我使用文件路径保存条目(mydocuments / .csv文件)我在WF上的显示是一个标签

问题:当我点击"显示数据"时,我创建的每个条目都会在一个连续的行中保存到csv / excel doc,也会在标签上保存。 我希望每个输入行在标签显示中分开 任何帮助将非常感谢,这个游戏的新手。 谢谢 G 我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

 namespace StringFilePath
 {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   string FilePath = Environment.GetFolderPath      (Environment.SpecialFolder.MyDocuments) +    Path.DirectorySeparatorChar+ "mestring.csv";
    private void btnAdd_Click(object sender, EventArgs e)
    {
        int id = int.Parse(txtID.Text);
        string fname = TXTfNAME.Text;
        string lname = txtLname.Text;
        string phone = txtPhone.Text;
        string email = txtEmail.Text;


        StreamWriter sw = File.AppendText(FilePath);
        sw.Write(id + ",");
        sw.Write(fname + ",");
        sw.Write(lname + ",");
        sw.Write(phone + ",");
        sw.Write(email + ",");

        sw.Close();


        txtID.Clear();
        TXTfNAME.Clear();
        txtLname.Clear();
        txtPhone.Clear();
        txtEmail.Clear();

    }

    private void isplay_Click(object sender, EventArgs e)
    {
        string content = File.ReadAllText(FilePath);
        lblDisplay.Text = content;
    }

1 个答案:

答案 0 :(得分:1)

您需要在文本中添加Environment.NewLine。您可以明确地执行此操作,也可以仅在最后一个输入

上使用sw.WriteLine
string line = $"{id},{fname},{lname},{phone},{email}";
using(StreamWriter sw = new StreamWriter(FilePath))
   sw.WriteLine(line);

或者更简洁

string line = $"{id},{fname},{lname},{phone},{email}{Environment.NewLine}";
File.AppendAllText(FilePath, line);

对于标签,您应该能够使用从文件加载的数据简单地设置其文本,但是,当然,标签应该具有足够的高度以显示加载的行