gpt4 book ai didi

c#将sql数据导出到csv

转载 作者:行者123 更新时间:2023-11-30 23:29:26 25 4
gpt4 key购买 nike

将我的数据从 sql 导出到 excel 时,它从第二行开始,而不是第一行。我想我已经将问题缩小到代码的 streamwriter 部分,但似乎无法找出问题所在!这是代码;

public static void ToCsv3(IDataReader myReader, string fileName, bool includeHeaderAsFirstRow)

{
const string Separator = ",";
Stream s = File.Create(fileName + ".txt");
StreamWriter streamWriter = new StreamWriter(s, Encoding.Unicode);


StringBuilder sb = null;

if (includeHeaderAsFirstRow)
{
sb = new StringBuilder();
for (int index = 0; index < myReader.FieldCount; index++)
{
if (myReader.GetName(index) != null)
sb.Append(myReader.GetName(index));

if (index < myReader.FieldCount - 1)
sb.Append(Separator);
}
streamWriter.WriteLine(sb.ToString());
}
int j = 0;
while (myReader.Read())
{
sb = new StringBuilder();


for (int index = 0; index < myReader.FieldCount - 1; index++)
{


if (!myReader.IsDBNull(index))
{
string value = myReader.GetValue(index).ToString();
if (myReader.GetFieldType(index) == typeof(String))
{
if (value.IndexOf("\"") >= 0)
value = value.Replace("\"", "\"\"");
if (value.IndexOf(Separator) >= 0)
value = "\"" + value + "\"";
}
if (j != 0)
{
if (index == 0)
{
sb.Append(Environment.NewLine);
}
}
sb.Append(value);

j = j + 1;
}


if (index < myReader.FieldCount - 1)
sb.Append(Separator);

}


if (!myReader.IsDBNull(myReader.FieldCount - 1))
sb.Append(myReader.GetValue(myReader.FieldCount).ToString().Replace(Separator, " "));


streamWriter.Write(sb.ToString());
}



myReader.Close();
streamWriter.Close();


}

最佳答案

我宁愿将解决方案分解为创建 CSV 并将其保存到文件中:

public static IEnumerable<String> ToCsv(IDataReader reader, 
Boolean includeHeaderAsFirstRow,
Char separator = ',',
Char quotation = '"') {

if (null == reader)
throw new ArgumentNullException("reader");

String qt = quotation.ToString();

StringBuilder Sb = new StringBuilder();

if (includeHeaderAsFirstRow) {
for (int i = 0; i < reader.FieldCount; ++i) {
if (i > 0)
Sb.Append(separator);

String name = reader.GetName(i);

if (name.Contains(separator) || name.Contains(quotation))
name = qt + name.Replace(qt, qt + qt) + qt;

Sb.Append(name);
}

yield return Sb.ToString();
}

while (reader.Read()) {
Sb.Clear();

for (int i = 0; i < reader.FieldCount; ++i) {
if (i > 0)
Sb.Append(separator);

if (!reader.IsDBNull(i)) {
String item = Convert.ToString(reader[i]);

if (item.Contains(separator) || item.Contains(quotation))
item = qt + item.Replace(qt, qt + qt) + qt;

Sb.Append(item);
}
}

yield return Sb.ToString();
}
}

public static void CsvToFile(String fileName,
IDataReader reader,
Char separator = ',',
Char quotation = '"') {

if (String.IsNullOrEmpty(Path.GetExtension(fileName)))
fileName += ".txt"; // ".csv" looks better here

File.WriteAllLines(fileName, ToCsv(reader, separator, quotation));
}

关于c#将sql数据导出到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com