导出数据到Excel
SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "导出Excel (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出文件保存路径"; string time = DateTime.Now.ToShortDateString().ToString(); time = time.Replace('/', '-'); saveFileDialog.FileName = "出库申请单" + time; saveFileDialog.OverwritePrompt = false; saveFileDialog.ShowDialog(); System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = true; if (excel == null) { MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; sheet.Name = "出库申请单"+ " " +time; List<string> columknHeader = new List<string>(); columknHeader.Add("上料顺序"); columknHeader.Add("板件编号"); columknHeader.Add("板件名称"); columknHeader.Add("需求量"); columknHeader.Add("板材所在仓库堆位"); excel.Visible = true; for (int i = 0; i < columknHeader.Count; i++) { excel.Cells[1, i + 1] = " " + columknHeader[i]; } List<string> plateIDList = new List<string>(); List<Plate> plateLists = HandleStockLoadingData.getInstance().GetAllPlate(); foreach (Plate vPlate in plateLists) { if (!plateIDList.Contains(vPlate.ID)) { plateIDList.Add(vPlate.ID); } } List<PlateAndBatchInfo> PlateInfo; GetSchedulingPlateAndBatchInfo(plateIDList,out PlateInfo); for (int i = 0; i < PlateInfo.Count; i++) { string[] str = new string[5]; str[0] = (i + 1).ToString(); str[1] = PlateInfo[i].PlateMode; str[2] = PlateInfo[i].PlateName; str[3] = PlateInfo[i].Count.ToString()+"张"; if (plateLists != null) { List<Plate> plate = plateLists.Where(x => x.MatMaterial == str[1]).ToList(); if (plate != null) { str[4] = plate.First().Location; } } for (int x = 0; x < columknHeader.Count; x++) { if (x == 0||x==3) { excel.Cells[i + 2, x + 1] = str[x]+"\t "; } else { excel.Cells[i + 2, x + 1] = str[x]; } } } sheet.Columns.ColumnWidth = 30; excel.DisplayAlerts = false; try { sheet.SaveAs(saveFileDialog.FileName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); } catch { MessageBox.Show("出库申请单导出失败!", "提示"); } excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); GC.Collect(); MessageBox.Show("出库申请单导出成功!", "提示");