读取sql文件并写入csv文件

时间:2014-07-16 14:13:45

标签: c# csv

我为用户创建了一个程序来访问数据库,然后选择一家公司并为该公司运行5个不同的sql查询,为每个公司创建csv文件。

问题出在我的一个csv文件中,有些数据没有显示在右栏中。

private void btnEmployees_Click(object sender, EventArgs e)
{
    string employees = File.ReadAllText("X:/ZoddsandEnds/Emer/SQL/Employees.txt");
    string accessConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + dataAddress + ";Persist Security Info=False;";
    string accessSelectEmployee = employees;
    OleDbConnection accessConnection = null;

    try
    {
        accessConnection = new OleDbConnection(accessConnect);
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error has occurred, failed to connect to the database.\r\n" + ex);
    }

    try
    {
        OleDbCommand accessCommand = new OleDbCommand(accessSelectEmployee, accessConnection);
        OleDbDataAdapter accessDataAdapter = new OleDbDataAdapter(accessCommand);

        accessConnection.Open();
        accessDataAdapter.Fill(accessDataSet, "employee");
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error has occurred, failed to retrieve data from the database.\r\n" + ex);
        return;
    }
    finally
    {
        accessConnection.Close();
    }

    string csvFileName = dataAddress.Replace(".mcp", "Employee.csv");

    using (StreamWriter sWriter = new StreamWriter(csvFileName))
    {
        sWriter.WriteLine("Reference, Gender, Title, Forename, Surname, Address1, Address2, Address3, Address4, Postcode, Country, Marital Status, Birth Date, Employment Status, Start Date, Leave Date," +
                        "Leaver, P45_1_IF_Required, Directorship Start Date, Branch, Cost Centre, Department, Run Group, Default Cost Split, NI Number, NI Letter, Tax Code, Week1/Month1, Tax Code Change Type," +
                        "Frequency, Payment Method, Bank Account No, Bank Account Name, Sort Code, Bank Name, Bank Branch, Building Society Ref, Autopay Ref, Taxable Pay Previous Employment, Taxable Pay This Employment," +
                        "Tax Previous Employment, Tax This Employment, NetPay To Date, Directors Earnings To Date, BF NI Letter, BF NI Calculation Basis, BF Earnings To LEL, BF Earnings To SET," +
                        "BF Earnings to PET, BF Earnings To UAP, BF Earnings To UEL, BF Earnings Above UEL, BF Ee Contributions Pt1, BF Ee Contributions Pt2, BF Er Contributions, BF Ee Rebate, BF Er Rebate, BF Ee Reduction," +
                        "StudentLoanFromDate, StudentLoanToDate, StudentLoanDeducted, Email, EeNIPdByErTD, ExPatExempt, DateOfArrival, TaxExemptPcnt,TaxExemptIncomeTD, TaxExemptGUIncomeTD, EeGuOverride, CalcEeGrossToNetFirst, NoNIGU, GrossUpPensionContribs, GUStudentLoan," +
                        "Double tax agreement, Foreign tax credit, UK Tax YTD, Foreign Tax YTD, TransferDate, Standard Hours, Worker Subject to Postponement Period, Postponement End Date, Postponement period Part Periods Allowed, Jobholder Opt In Notice Received," +
                        "Entitled Worker Active Membership Start, Passport Number, Starting Declaration, Irregular Emloyement, Omit From RTI, Payment to a Non Individal,Old RTI Ee Reference, P45(3) Tax Office Number, P45(3) Tax Office Reference, P45(3) Leave Date, P45(3) Tax Code, P45(3) Week 1 Month 1, P45(3) Tax Period- Monthly/Weekly, P45(3) Tax Period - Period Number, P45(3) Previous Tax Year," +
                        "P45(3) Previous Pay, P45(3) Previous Tax, P45(3)Student Loan, P46 Statement A,B or C, P46 Student Loans (Box D), P46 (pen) Tax Office Number, P46 (Pen) Tax Office Reference, P46 (Pen) Leave Date, P46(Pen) Tax Code, P46(Pen) Week 1 Month 1," +
                        " P46(Pen) Tax Period - Monthly/Weekly, P46(Pen) Tax Period - Period Number, P46(Pen) Previous Tax Year, P46(Pen) previous Pay, P46(Pen) Previous Tax, P46 (Pen) Annual Pension, P46(Pen) Is Recently Bereaved, P46(Expat) Statement A, B or C" +
                        "P46 (Expat Student Loan Indicator, P46 (Expat) EEA or Commonwealth Citizen, P46 (Expat) EPM6 Scheme,");

        DataRowCollection accessDRC = accessDataSet.Tables["employee"].Rows;
        int colCount = accessDataSet.Tables["employee"].Columns.Count;

        foreach (DataRow accessDR in accessDRC)
        {
            string csvline = "";

            for (int i = 0; i < colCount; i++)
            {
                csvline = csvline + accessDR[i] + ",";
            }
            sWriter.WriteLine(csvline);
        }
        accessDataSet.Tables["employee"].Clear();
    }
}

以下是csv文件显示数据的方式示例:

![以下是csv文件显示数据的方式示例] [1]

1 个答案:

答案 0 :(得分:0)

正如Marc Gravell所说,对于那些行,你的数据可能还有一个额外的逗号...看起来你在Excel中查看结果,你是否将原始csv文件看作文本文件? ?这应该会告诉你为什么这些线看起来不同。您只需要小心复制数据而不处理数据库中的逗号,换行符等。问我怎么知道;)

您可以在Excel的每个字符串周围添加双引号,将其解释为文本,并忽略字符串中的逗号,如下所示:

csvline = csvline + "\"" + accessDR[i] + "\"" + ",";