我到处寻找我的问题的答案,但我似乎无法弄明白。我尝试使用excellibrary在Create Excel (.XLS and .XLSX) file from C#中描述的方法,并创建了excel文件,但数据已完全销毁且无法恢复。在asp.net应用程序中将数据从mysql导出到excel的最佳方法是什么?
DataSet ds = new DataSet("New_Dataset");
DataTable dt = new DataTable("New_DataTable");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
MySqlConnection con = new MySqlConnection(GetConnectionString());
con.Open();
string sql = "SELECT * FROM reportdata WHERE TakenDate =?Date";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlParameter[] param = new MySqlParameter[1];
param[0] =new MySqlParameter("?Date", MySqlDbType.VarChar, 10);
param[0].Value = txtStartDate.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
adapt.SelectCommand = cmd;
adapt.Fill(dt);
con.Close();
ds.Tables.Add(dt);
string strDay = DateTime.Now.DayOfWeek.ToString();
string day = DateTime.Now.Day.ToString();
string month = DateTime.Now.Month.ToString();
string year = DateTime.Now.Year.ToString();
ExcelLibrary.DataSetHelper.CreateWorkbook(@"G:\Reports\Report " + strDay + " " + month + "-" + day + "-" + year + ".xls", ds);
答案 0 :(得分:0)
考虑使用NPOI Library。我发现它非常容易使用,并利用它来制作quick Excel spreadsheet dump from GridView results。我相信你可以用类似的方式应用技术。我的代码的核心就像这样简单:
DocInfo = PropertySetFactory.CreateDocumentSummaryInformation();
DocInfo.Company = "Dillie-O Digital";
Workbook.DocumentSummaryInformation = DocInfo;
SummaryInfo = PropertySetFactory.CreateSummaryInformation();
SummaryInfo.Subject = "Soup to Nuts GridView Export Example";
Workbook.SummaryInformation = SummaryInfo;
DataSheet = Workbook.CreateSheet("Employees");
for(int i = 0; i <= GridData.Rows.Count - 1; i++)
{
CurrRow = DataSheet.CreateRow(i);
for(int j = 0; j <= GridData.Rows[i].Cells.Count - 1; j++)
{
if(!IgnoreColumns.Contains(j))
{
CurrCell = CurrRow.CreateCell(i);
CurrCell.SetCellValue(GridData.Rows[i].Cells[j].Text);
}
}
}
ResultStream = new FileStream(EndPath, FileMode.Create);
Workbook.Write(ResultStream);
ResultStream.Close();
答案 1 :(得分:0)
我发现GemBox.Spreadsheet效果很好而且它是免费的! http://www.gemboxsoftware.com/
以下我的代码使用数据表来填充Excel电子表格:
// Creating the Excel file with Gembox
ExcelFile ef = new ExcelFile();
foreach (DataTable dt1 in ds.Tables)
{
ExcelWorksheet ws = ef.Worksheets.Add(dt1.TableName);
ws.InsertDataTable(dt1, "A1", true);
}