从DataGrid导出数据到Excel
string logPath = Environment.CurrentDirectory + @"\GradeLogs";
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(@logPath);
}
string fileName = string.Format("{0}_{1}.xls",LotID, DateTime.Now.ToString("yyyyMMdd HHmmss"));
string filePath = string.Format("{0}\\{1}", logPath, fileName);
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
foreach (TabPage tmpPage in tab_Main.TabPages)
{
string tmpSheetName = tmpPage.Text;
CommonGrid grid = (CommonGrid)tmpPage.Controls[0];
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(tmpSheetName);
int colCount = 0;
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < grid.Columns.Count; i++)
{
if (grid.Columns[i].Visible)
{
NPOI.SS.UserModel.ICell cell = headerRow.CreateCell(colCount++, NPOI.SS.UserModel.CellType.String);
cell.SetCellValue(grid.Columns[i].HeaderText);
}
}
int rowCount = 1;
for (int i = 0; i < grid.Rows.Count; i++)
{
colCount = 0;
if (grid.Rows[i].Visible)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowCount++);
for (int j = 0; j < grid.Columns.Count; j++)
{
if (grid.Columns[j].Visible)
{
NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(colCount++, NPOI.SS.UserModel.CellType.String);
if (grid.Rows[i].Cells[j].Value != null)
{
cell.SetCellValue(grid.Rows[i].Cells[j].Value.ToString());
}
else
{
cell.SetCellValue(string.Empty);
}
}
}
}
}
for (int i = 0; i < grid.Columns.Count; i++)
{
if (grid.Columns[i].Visible)
{
sheet.AutoSizeColumn(i);
}
}
}
workbook.Write(ms);
FileStream file = new FileStream(@filePath, FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
ms.Close();
ms.Dispose();

浙公网安备 33010602011771号