/// <summary>
/// 导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExport_Click(object sender, EventArgs e)
{
try
{
string saveFileName = DateTime.Now.Ticks + "异常建筑信息.xls";
string buildingName = this.txtBuildName.Text;//建筑物名称
string buildID = this.txtBuildID.Text.Trim();//建筑物编号
string cityCode = "";
DateTime starthour = DateTime.Parse("2000-01-01");
DateTime endHour = DateTime.Parse("9999-12-31");
string exceptionState = "";//异常标志
int totalCount = 0;
DataTable exceptionList =BLL.Proc_GetBuildList(1, int.MaxValue / 2, buildingName, buildID, cityCode, starthour, endHour, exceptionState, ref totalCount);
fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
//(Optional) set the width of the columns
sheet.SetColumnWidth(0, 12 * 256);
sheet.SetColumnWidth(1, 40 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 20 * 256);
//Create a header row
var headerRow = sheet.CreateRow(0);
//Set the column names in the header row
headerRow.CreateCell(0).SetCellValue("序号");
headerRow.CreateCell(1).SetCellValue("建筑物名称");
headerRow.CreateCell(2).SetCellValue("建筑物编号");
headerRow.CreateCell(3).SetCellValue("条数");
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
if (exceptionList == null || exceptionList.Rows == null || exceptionList.Rows.Count <= 0)
{
return;
}
//Populate the sheet with values from the grid data
for (int i = 0; i < exceptionList.Rows.Count; i++)
{
//Create a new row
var row = sheet.CreateRow(rowNumber++);
//Set values for the cells
row.CreateCell(0).SetCellValue(exceptionList.Rows[i]["seq"].ToString());
row.CreateCell(1).SetCellValue(exceptionList.Rows[i]["BuildID"].ToString());
row.CreateCell(2).SetCellValue(exceptionList.Rows[i]["BuildName"].ToString());
row.CreateCell(3).SetCellValue(exceptionList.Rows[i]["num"].ToString());
}
//bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = saveFileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
if (saveFileName != "")
{
try
{
fs = File.OpenWrite(saveDialog.FileName);
workbook.Write(fs);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
}
finally
{
if (fs != null)
fs.Close();
GC.SuppressFinalize(this);
}
}