我正在将数据从SQLite导出到.csv
,但我在行上遇到问题,为什么结果总是出现在第一行?我错过了什么吗?
结果:
我的代码:
private void DataExport()
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Title = "Choose file to save to",
FileName = ".csv",
Filter = "CSV (*.csv)|*.csv",
FilterIndex = 0,
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (saveFileDialog.ShowDialog() == true)
{
SQLiteCommand cmd = new SQLiteCommand();
String sSQL;
sSQL = "select * from Tile1";
cmd.CommandText = sSQL;
clsCon.con.Open();
cmd.Connection = clsCon.con;
SQLiteDataReader dr2;
dr2 = cmd.ExecuteReader();
dr2.Read();
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
for (var i = 0; i < dr2.FieldCount; i++)
{
_dataTable.Columns.Add("" + dr2.GetName(i) + "", typeof(string));
_dataTable.Rows.Add("" + dr2.GetValue(i) + "");
}
var rows = _dataTable.Rows;
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = _dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(saveFileDialog.FileName, sb.ToString());
clsCon.con.Close();
}
}
答案 0 :(得分:0)
它看起来没有正确填充DataTable对象,请检查此处的部分:
for (var i = 0; i < dr2.FieldCount; i++)
{
_dataTable.Columns.Add("" + dr2.GetName(i) + "", typeof(string));
_dataTable.Rows.Add("" + dr2.GetValue(i) + "");
}
我猜你试图在这里设置数据表的列,但是你不能在同一时间追加行,你实际上是将第一行的每个列值添加到不同的行中。您生成的表格如下:
col1 col2 col3 col4
row1 val(1,1)
row2 val(1,2)
row3 val(1,3)
row4 val(1,4)
val(x,y)表示第y列的值和数据库中的第x行。
@Darin Dimitrov的解决方案非常适合您的问题。
答案 1 :(得分:-1)
尝试简化你的代码,我的意思是那些DataTables和DataSets让我疯狂:
private void DataExport()
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Title = "Choose file to save to",
FileName = ".csv",
Filter = "CSV (*.csv)|*.csv",
FilterIndex = 0,
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (!saveFileDialog.ShowDialog())
{
return;
}
using (var conn = new SQLiteConnection(ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM Tile1";
using (var reader = cmd.ExecuteReader())
using (var writer = new StreamWriter(saveFileDialog.FileName))
{
var columnNames = Enumerable
.Range(0, reader.FieldCount)
.Select(reader.GetName);
string header = string.Join(", ", columnNames);
writer.WriteLine(header);
while (reader.Read())
{
var values = Enumerable
.Range(0, reader.FieldCount)
.Select(reader.GetValue);
string valuesRow = string.Join(", ", values);
writer.WriteLine(valuesRow);
}
}
}
}