1

I successfully imported following file in database but my import method removes double quotes during saving process. but i want to export this file as it is , i.e add quotes to a string which contains delimiter so how to achieve this .

here is my csv file with headers and 1 record.

PTNAME,REGNO/ID,BLOOD GRP,WARD NAME,DOC NAME,XRAY,PATHO,MEDICATION,BLOOD GIVEN
Mr. GHULAVE VASANTRAO PANDURANG,SH1503/00847,,RECOVERY,SHELKE SAMEER,"X RAY PBH RT IT FEMUR FRACTURE    POST OP XRAY   -ACCEPTABLE WITH IMPLANT IN SITU    2D ECHO MILD CONC LVH  GOOD LV SYSTOLIC FUN,  ALTERED LV DIASTOLIC FUN.",  HB-11.9gm%  TLC-8700  PLT COUNT-195000  BSL-173  UREA -23  CREATININE -1.2  SR.ELECTROLYTES-WNR  BLD GROUP-B +  HIV-NEGATIVE  HBsAG-NEGATIVE  PT INR  -15/15/1.0.    ECG  SINUS TACHYCARDIA  ,IV TAXIMAX 1.5 GM 1-0-1      IV TRAMADOL DRIP 1-0-1      TAB NUSAID SP     1-0-1      TAB ARCOPAN D 1-0-1      CAP BONE C PLUS 1 -0-1      TAB ANXIT 0.5 MG 0-0-1        ANKLE TRACTION 3 KG RT LL  ,NOT GIVEN

Here is my method of export:

    public void DataExport(string SelectQuery, string fileName)
    {
        try
        {
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(SelectQuery, con);
            da.Fill(dt);

            //Sets file path and print Headers
          //  string filepath = txtreceive.Text + "\\" + fileName;
            string filepath = @"C:\Users\Priya\Desktop\R\z.csv";
            StreamWriter sw = new StreamWriter(filepath);

            int iColCount = dt.Columns.Count;

            // First we will write the headers if IsFirstRowColumnNames is true: //  
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);

                if (i < iColCount - 1)
                {
                    sw.Write(',');
                }
            }
            sw.Write(sw.NewLine);

            foreach (DataRow dr in dt.Rows) // Now write all the rows.
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }

                    if (i < iColCount - 1)
                    {
                        sw.Write(',');
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
        }
        catch { }
    }
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Member 1
  • 23
  • 8
  • Do look at "LinqToExcel" as a very simple alternative to reading CSV files. Your code can get as simple as `var query = from x in xl.Worksheet() select x["XRAY"].Cast();`. – Enigmativity Apr 27 '15 at 11:39
  • i solved above issue myself and successfully inserted string in database but it saved in database by removing double quotes but now at the time of export i want to join double quotes again as it is in string how to do this. – Member 1 Apr 28 '15 at 05:13
  • I don't think removing double-quotes from the database end would help - you'd just end up splitting fields with the commas in them into multiple fields and break the CSV. – Enigmativity Apr 28 '15 at 05:51
  • so then how to store string with double quotes – Member 1 Apr 28 '15 at 05:58
  • Ah, sorry, I got it wrong - and so did @nvoigt - you're not parsing the CSV, you're generating it from the database. Is that right? – Enigmativity Apr 28 '15 at 06:01
  • Yes, i have to generate it from database and i want to add quotes around string which contains comma as here (xray) filed – Member 1 Apr 28 '15 at 06:35
  • You should remove the code that parses the CSV from your question. It mislead everyone in to thinking you were parsing. – Enigmativity Apr 28 '15 at 07:00

2 Answers2

0
if (myString.Contains(","))
{
    myWriter.Write("\"{0}\"", myString);
}
else
{
    myWriter.Write(myString);
}
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
0

The very simplest thing that you can do is replace the line sw.Write(dr[i].ToString()); with this:

var text = dr[i].ToString();
text = text.Contains(",") ? String.Format("\"{0}\"", text) : text;
sw.Write(text);

However, there are quite a few other issues with your code - most importantly you are opening a lot of disposable resources without disposing them properly.

I'd suggest a bit of a rewrite, like this:

public void DataExport(string SelectQuery, string fileName)
{
    using (var dt = new DataTable())
    {
        using (var da = new SqlDataAdapter(SelectQuery, con))
        {
            da.Fill(dt);

            var header = String.Join(
                ",",
                dt.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName));

            var rows =
                from dr in dt.Rows.Cast<DataRow>()
                select String.Join(
                    ",",
                    from dc in dt.Columns.Cast<DataColumn>()
                    let t1 = Convert.IsDBNull(dr[dc]) ? "" : dr[dc].ToString()
                    let t2 = t1.Contains(",") ? String.Format("\"{0}\"", t1) : t1
                    select t2);

            using (var sw = new StreamWriter(fileName))
            {
                sw.WriteLine(header);
                foreach (var row in rows)
                {
                    sw.WriteLine(row);
                }
                sw.Close();
            }
        }
    }
}

I've also broken apart the querying of the data from the data adapter from the writing of the data to the stream writer.

And, of course, I'm adding double-quotes to text that contains commas.

The only other thing I was concerned about was the fact that con is clearly a class-level variable and it is being left open. That's bad. Connections should be opened and closed each time they are used. You should probably consider making that change too.

You could also remove the stream write entirely by replacing that block with this:

File.WriteAllLines(fileName, new [] { header }.Concat(rows));

And, finally, wrapping your code in a try { ... } catch { } is just a bad practice. It's like saying "I'm writing some code that could fail, but I don't care and I don't want to be told if it does fail". You should only even catch specific exceptions that you do deal with. In this code you should consider catching file exceptions like running out of hard drive space, or writing to a read-only file, etc.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172