I want to get SQL data and export it to a .CSV
file, but when exporting my data from SQL to Excel, the code can export the .CSV
file but it is empty. I have checked the SQL command in database, it does get data from database.
What's wrong with my code?
This is the code:
Controller.cs :
.......
string SQL = "select RoomId, Name,Tel,Sdate,Edate from StayDormApplications";
DataTable qdt = new DataTable();
qdt = Co.GetData(SQL);
var roommapplications = ConvertDataTable<OutputClass>(qdt).AsQueryable();
var venueregisters = _db.StayDormApplications.OrderByDescending(p => p.Sdate).AsQueryable();
if (mode == "export")
{
var export = ConvertList<OutputClass>(roommapplications.OrderByDescending(x => x.Sdate).ToList());
DateTime now = DateTime.Now;
string today = now.Year.ToString() + "_" + now.Month.ToString("00") + "_" + now.Day.ToString("00");
new ExcelFactory().ExportExcel("outputCSV" + today, export, "/upfiles/ExcelTemplate/HA04.xlsx", Response);
string mode2 = "";
SndaFun.SetFilterString(ref mode2, mode);
ViewBag.mode = mode2;
}
//end export
return View(dormapplicationList.OrderByDescending(p => p.Sdate)
.ToPagedList(currentPageIndex, DefaultPageSize));
}
.....
public static DataTable ConvertList<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
? Nullable.GetUnderlyingType(prop.PropertyType)
: prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
public void ExportExcel(string fileName, DataTable dt, string path, HttpResponseBase response)
{
FileStream file = new FileStream(HostingEnvironment.MapPath(path), FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = DataTableToWorkbook(new XSSFWorkbook(file), dt);
response.Clear();
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
string.Format("attachment; filename=" + fileName + ".xlsx"));
response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + System.Web.HttpUtility.UrlEncode("" + fileName + "" + ".xlsx", System.Text.Encoding.UTF8)));
//response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.BinaryWrite(ms.ToArray());
workbook.Close();
ms.Close();
ms.Dispose();
response.End();
}
My ExcelTemplate/HA04.xlsx
has five columns:
RoomId, Name, Tel, Sdate, Edate