我想通過特定名稱從數據庫中導出csv文件,例如患者數據包含「病房名稱」字段爲「GENERAL WARD(FEMALE)」,那麼生成的文件名必須爲「GENF.csv」。我試着用開關盒,但它不工作。如果有任何更改,請編輯。如何導出具有特定名稱的csv文件?
謝謝。
下面是代碼:
//Function declares methods to export
public void ExportAll() {
try {
int i = 0;
for (int icount = 0; icount <= 400; icount++) {
object o = saiNathHospitalDataSet.Tables["PatientTable"].Rows[i]["WARD NAME"];
object obj = saiNathHospitalDataSet.Tables["PatientTable"].Rows[i]["PTNAME"];
int swichexpression = 9;
object a = "GENERAL WARD (FEMALE)";
object b = "GENERAL WARD (MALE)";
object c = "RECOVERY";
object d = "SEMI DELUXE 02";
object e = "SEMI DELUXE 05";
object f = "SEMI DELUXE 06";
object g = "ICU";
object h = "SEMI SPECIAL 03";
object j = "SEMI SPECIAL 01";
switch (swichexpression) {
case 1:
if (o == a) {
// o = "GENF";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "GENF.csv");
}
break;
case 2:
if (o == b) {
// o = "GENM";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "GENM.csv");
}
break;
case 3:
if (o == c) {
//o = "REC";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "REC.csv");
}
break;
case 4:
if (o == d) {
// o = "SDELX02";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "SDELX02.csv");
}
break;
case 5:
if (o == e) {
// o = "SDELX05";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "SDELX05.csv");
}
break;
case 6:
if (o == f) {
// o = "SDELX06";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "SDELX06.csv");
}
break;
case 7:
if (o == g) {
//o = "ICU";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "ICU.csv");
}
break;
case 8:
if (o == h) {
//o = "SSPEC03";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "SSPEC03.csv");
}
break;
case 9:
if (o == j) {
//string z = "SSPEC01";
DataExport("select * from PatientTable where [WARD NAME] =" + o + "", "SSPEC01.csv");
}
break;
}
//DataExport("select * from PatientTable", "" + s + ".csv");
i++;
}
}
catch {
}
}
編輯::數據導出方法,
public void DataExport(string SelectQuery, string fileName)
{
try
{
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(txtreceive.Text + "\\" + fileName))
{
sw.WriteLine(header);
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Close();
}
}
}
}
catch { }
}
什麼是'DataExport'?它應該從哪裏得到文件名? –
請正確縮進您的代碼並修復您的變量名稱,它們非常可怕。給'string'變量一個靜態類型 - 'string's。處理可能的例外情況。 –