git_bsmd/AIS/puls200.AIS2Excel/AISVessel.cs
2019-05-12 19:59:53 +00:00

71 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace puls200.AIS2Excel
{
public static class AISVessel
{
const string ExportQuery = "SELECT aisposreport.MMSI, aisposreport.timestamp, aisposreport.latitude, aisposreport.longitude, aisposreport.stationid, aisposreport.cog, aisposreport.heading, aisposreport.navstatus, aisstaticdata.callsign, aisstaticdata.name, aisstaticdata.shiptype, aisstaticdata.classb, aisstaticdata.shipdescription " +
"FROM aisstaticdata JOIN aisposreport ON aisposreport.mmsi = aisstaticdata.mmsi " +
"WHERE lat lon timestamp ORDER BY posreport.timestamp";
public static void Export(DateTime from, DateTime to, double ulLat, double ulLon, double lrLat, double lrLon, string filename)
{
using (StreamWriter sw = new StreamWriter(filename))
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(ExportQuery, con);
IDataReader reader = cmd.ExecuteReader();
createCsvFile(reader, sw);
reader.Close();
con.Close();
}
}
public static void createCsvFile(IDataReader reader, StreamWriter writer)
{
const string Delimiter = "\"";
const string Separator = ",";
// write header row
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}
writer.Write(Delimiter + reader.GetName(columnCounter) + Delimiter);
}
writer.WriteLine(string.Empty);
// data loop
while (reader.Read())
{
// column loop
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}
writer.Write(Delimiter + reader.GetValue(columnCounter).ToString().Replace('"', '\'') + Delimiter);
} // end of column loop
writer.WriteLine(string.Empty);
} // data loop
writer.Flush();
}
}
}