/// <summary> /// Создает файл формата .doc /// </summary> /// <param name="path">Путь к Excel файлу, из которого берется таблица.</param> private void CreateWordFile(string path) { Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); workbook.LoadFromFile(path); Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; Document doc = new Document(); Table table = doc.AddSection().AddTable(true); table.ResetCells(sheet.LastRow, sheet.LastColumn); for (int r = 1; r <= sheet.LastRow; r++) { for (int c = 1; c <= sheet.LastColumn; c++) { CellRange xCell = sheet.Range[r, c]; TableCell wCell = table.Rows[r - 1].Cells[c - 1]; TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText); } } for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Rows[i].Cells.Count; j++) { table.Rows[i].Cells[j].Width = 100f; } } doc.SaveToFile("result.doc", Spire.Doc.FileFormat.Docx); System.Diagnostics.Process.Start("result.doc"); }
public void ChangeExcel2Image(string filename) { Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); workbook.LoadFromFile(filename); Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; sheet.SaveToImage("选型结果.jpg"); //图片后缀.bmp ,imagepath自己设置 }
public void MergeAllSheet(GetTime gt) { Spire.Xls.Workbook wb = new Spire.Xls.Workbook(); wb.LoadFromFile(excelFilePath); Spire.Xls.Workbook destWorkbook = new Spire.Xls.Workbook(); Spire.Xls.Worksheet destSheet = destWorkbook.Worksheets[0]; wb.Worksheets["Sheet1"].AllocatedRange.Copy(destSheet.Range[1, 1]); destSheet.Range[1, 1].Text = string.Format("营盘壕煤矿{0}工作面矿压综合分析日报表", gt.getWorkFace()); int lastrow = destSheet.Range.RowCount; if (wb.Worksheets["Sheet2"] != null) { wb.Worksheets["Sheet2"].AllocatedRange.Copy(destSheet.Range[destSheet.Range.RowCount + 1, 1]); if (wb.Worksheets["Sheet3"] != null) { wb.Worksheets["Sheet3"].AllocatedRange.Copy(destSheet.Range[lastrow + 1, 11]); } for (int i = 4; i <= wb.Worksheets.Count + 6; i++) { if (wb.Worksheets["Sheet" + i.ToString()] != null) { wb.Worksheets["Sheet" + i.ToString()].AllocatedRange.Copy(destSheet.Range[destSheet.Range.RowCount + 1, 1]); } } } destWorkbook.SaveToFile(@"..\..\modelFile\" + string.Format("Excel_{0}.xls", gt.getDateToday())); }
public static void InitiExcel(string[] name) { Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); Spire.Xls.Worksheet newSheet1 = workbook.CreateEmptySheet("Crashes"); workbook.Worksheets.Remove("Sheet1"); workbook.Worksheets.Remove("Sheet2"); workbook.Worksheets.Remove("Sheet3"); newSheet1.Range["A1:M1"].ColumnWidth = 17; newSheet1.Range.HorizontalAlignment = HorizontalAlignType.Center; newSheet1.Range["B6"].Value = "Date"; for (int i = 1; i <= name.Length; i++) { newSheet1.Range[Convert.ToChar('B' + i).ToString() + "6"].Value = name[i - 1]; } newSheet1.Range[Convert.ToChar('B' + (name.Length + 1)).ToString() + "6"].Value = "All Crashes"; newSheet1.Range[Convert.ToChar('B' + (name.Length + 2)).ToString() + "6"].Value = "Percent Impacted"; newSheet1.Range[Convert.ToChar('B' + (name.Length + 3)).ToString() + "6"].Value = "Crashes/OS"; newSheet1.Range[Convert.ToChar('B' + (name.Length + 4)).ToString() + "6"].Value = "OS"; newSheet1.Range["B6:" + Convert.ToChar('B' + (name.Length + 4)).ToString() + "6"].BorderInside(LineStyleType.Thin, Color.LightBlue); newSheet1.Range["B6:" + Convert.ToChar('B' + (name.Length + 4)).ToString() + "6"].BorderAround(LineStyleType.Medium, Color.LightBlue); workbook.SaveToFile(System.Environment.CurrentDirectory + "\\RecentData.xlsx", ExcelVersion.Version2013); }
public void MergeAllSheet(GetTime gt) { Spire.Xls.Workbook wb = new Spire.Xls.Workbook(); wb.LoadFromFile(excelFilePath); Spire.Xls.Workbook destWorkbook = new Spire.Xls.Workbook(); Spire.Xls.Worksheet destSheet = destWorkbook.Worksheets[0]; for (int i = 1; i <= wb.Worksheets.Count + 6; i++) { if (wb.Worksheets["Sheet" + i.ToString()] != null) { wb.Worksheets["Sheet" + i.ToString()].AllocatedRange.Copy(destSheet.Range[destSheet.LastRow + 3, 1]); } } destWorkbook.SaveToFile(@"..\..\modelFile\" + string.Format("Excel_{0}.xls", gt.getDateToday())); }
private void export_Click(object sender, EventArgs e) { var path = @"D:\test\WorkOrder.xls"; var outPath = @"D:\\test\\aspose"; //HSSFWorkbook wk = null; //using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) //{ // wk = new HSSFWorkbook(fs); // fs.Close(); //} //ISheet sheet = wk.GetSheet("Sheet1"); using (Spire.Xls.Workbook workbook = new Spire.Xls.Workbook()) { workbook.LoadFromFile(path); Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; const string main_Dir = @"c:/WenTest"; if (!Directory.Exists(main_Dir)) { //Directory.CreateDirectory(main_Dir); } else { ExportImg.DeleteFolder(main_Dir); Directory.CreateDirectory(main_Dir); } //string mypath = Environment.CurrentDirectory+"\\test"; if (File.Exists(outPath)) { File.Delete(outPath); Directory.CreateDirectory(outPath); } else { Directory.CreateDirectory(outPath); } //sheet.SetRowHeightPixels() //sheet.SaveToImage(outPath+"\\msample.png"); sheet.SaveToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn).Save(outPath + "\\test.jpg"); //IWorkbook workbook = new IWorkbook(); } }
public static void GenerateChart(string[] name) { try { if (File.Exists(System.Environment.CurrentDirectory + "\\Trend Analysis.xlsx")) { File.Delete(System.Environment.CurrentDirectory + "\\Trend Analysis.xlsx"); } Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); Spire.Xls.Worksheet newSheet = workbook.CreateEmptySheet("Crashes"); workbook.Worksheets.Remove("Sheet1"); workbook.Worksheets.Remove("Sheet2"); workbook.Worksheets.Remove("Sheet3"); newSheet.Range["A1:M1"].ColumnWidth = 15; //newSheet.Range.HorizontalAlignment = HorizontalAlignType.Center; Spire.Xls.Workbook workbook1 = new Spire.Xls.Workbook(); workbook1.LoadFromFile(System.Environment.CurrentDirectory + "\\RecentData.xlsx"); //int lastRow = workbook1.Worksheets["Crashes"].LastRow; int lastRow = workbook1.Worksheets["Crashes"].LastRow; //workbook1.Worksheets["Crashes"].Range["B6:I6"].Copy(workbook.Worksheets["Crashes"].Range["A6:H6"]); //workbook1.Worksheets["Crashes"].Range["B" + (lastRow - 29) + ":I" + lastRow].Copy(workbook.Worksheets["Crashes"].Range["A7:H36"]); workbook1.Worksheets["Crashes"].Range["B6:" + Convert.ToChar('B' + (name.Length + 4)).ToString() + "6"].Copy(workbook.Worksheets["Crashes"].Range["A41:" + Convert.ToChar('A' + (name.Length + 4)).ToString() + "41"]); if (lastRow < 37) { workbook1.Worksheets["Crashes"].Range["B7" + ":" + Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow].Copy(workbook.Worksheets["Crashes"].Range["A42:" + Convert.ToChar('A' + (name.Length + 4)).ToString() + (lastRow + 25)]); } else { workbook1.Worksheets["Crashes"].Range["B" + (lastRow - 29) + ":" + Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow].Copy(workbook.Worksheets["Crashes"].Range["A42:" + Convert.ToChar('A' + (name.Length + 4)).ToString() + "71"]); } workbook.Worksheets["Crashes"].Range["A41:" + Convert.ToChar('A' + (name.Length + 4)).ToString() + (lastRow + 25)].HorizontalAlignment = HorizontalAlignType.Center; workbook.SaveToFile(System.Environment.CurrentDirectory + "\\Trend Analysis.xlsx", ExcelVersion.Version2013); } catch (Exception) { throw; } }
private void PutValue(string[] name, string title_name) { ws = wb.Worksheets[0]; for (int i = 1; i <= chart_len; i++) { //A2 2 1 行i+1列1 ws.Range[i + 1, 1].Text = name[i - 1]; string str = string.Format(sqlquary + @"AND CONVERT(varchar(100), AcquisitionTime, 8) LIKE '%:00:%' AND MsgForewarn.Memo = '{0}'", name[i - 1]); DataTable datatable = GetDataTable(str); DataRow[] dataRows = datatable.Select(); for (int j = 0, k = 0; k < dataRows.Length; j++, k = k + 3) { //B1 C1 D1 ws.Range[1, j + 2].Text = dataRows[k]["Time"].ToString(); ws.Range[i + 1, j + 2].NumberValue = Math.Round(double.Parse(dataRows[k]["Value"].ToString()), 2); } } ChartDraw(title_name); }
static void Main(string[] args) { try { Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\temp\CFRI_Clinical_DB_Approved_Studies_v24.xlsx"); //Initailize worksheet Worksheet sheet = workbook.Worksheets[0]; DataTable dataTable = sheet.ExportDataTable(); DataTableToJsonObj(dataTable); Console.ReadKey(); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadKey(); } }
/// <summary> /// 导出 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">数据源</param> /// <param name="title">列名</param> /// <param name="fileName">文件名</param> public static void Except <T>(IEnumerable <T> collection, string title, string fileName) { var tb = Utility.ToDataTable(collection); Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; sheet.InsertDataTable(tb, true, 1, 1); var dataRow = sheet.Rows[0]; var strColumns = title; string[] strArry = strColumns.Split(','); for (int i = 0; i < strArry.Length; i++) { dataRow.Cells[i].Value = strArry[i]; } var resp = System.Web.HttpContext.Current.Response; workbook.SaveToHttpResponse(fileName + ".xls", resp); resp.Flush(); resp.End(); }
public static void LoadData(Spire.Xls.Workbook workbook, string[] name, string arg, Dictionary <string, string[]> condition) { driverData = new Dictionary <string, List <string> >(); Spire.Xls.Worksheet sheet = workbook.Worksheets["Crashes"]; int lastRow = sheet.Range.LastRow; //2020/10/12 0:00:00 String path = arg == "NET" ? NetPath : Path; //string[] fileName = Directory.GetFiles(System.Environment.CurrentDirectory + "\\ExportData", "*.csv"); string[] fileName = Directory.GetFiles(path, "Reliability-Crashes_Total*.csv"); string[] fileName1 = Directory.GetFiles(path, "OSAdoption-TMAD*.csv"); string firstDate = DateTime.Now.Year.ToString() + "/" + fileName[0].Split("Total-")[1].Split(".")[0].Split("-")[1] + "/" + fileName[0].Split("Total-")[1].Split(".")[0].Split("-")[2]; //获取文件列表中第一项文件日期 //string lastDate = DateTime.Now.Year.ToString() + "/" + fileName[^1].Split("Total-")[1].Split(".")[0].Split("-")[0] + "/" + fileName[^1].Split("Total-")[1].Split(".")[0].Split("-")[1]; string[] date_1 = sheet.Range["B" + lastRow].Value == "Date" ? firstDate.Split("/") : sheet.Range["B" + lastRow].Value.Split(" ")[0].ToString().Split("/"); DateTime dateTime = new DateTime(Convert.ToInt32(date_1[0]), Convert.ToInt32(date_1[1]), Convert.ToInt32(date_1[2])); string curr_Date = DateTime.Now.ToString("yyyy-MM-dd"); string curr_Date1 = DateTime.Now.ToString("yyyy/M/dd"); bool flag = readCSV(path + $"\\Reliability-Crashes_Date-{curr_Date}.csv", out DataTable t); if (flag == false) { for (int i = 0; i < 10; i++) { flag = readCSV(path + $"\\Reliability-Crashes_Date-{DateTime.Now.AddDays(-1)}.csv", out t); if (flag) { break; } } } string reportDate = t.Rows[0].ItemArray[0].ToString().Split(" ")[2];//Report Date : 2020-12-05 for (int i = 0; i < fileName.Length; i++) { int lastRow1 = sheet.Range.LastRow + 1; string date = DateTime.Now.Year.ToString() + "/" + fileName[i].Split("Total-")[1].Split(".")[0].Split("-")[1] + "/" + fileName[i].Split("Total-")[1].Split(".")[0].Split("-")[2]; DateTime new_date1 = Convert.ToDateTime(date); if (sheet.Range["B" + lastRow].Value == "Date" || DateTime.Compare(sheet.Range["B" + lastRow].DateTimeValue, new_date1) < 0) { string fullpath = fileName[i]; string fullpath1 = fileName[i].Replace(Crashes_Total, TMAD); readCSV(fullpath, out DataTable dt); sheet.Range["B" + lastRow1].DateTimeValue = new_date1; int[] result = GetCrashes2(dt, condition); for (int x = 1; x <= name.Length; x++) { sheet.Range[Convert.ToChar('B' + x).ToString() + lastRow1].NumberValue = result[0]; } sheet.Range[Convert.ToChar('B' + (name.Length + 1)).ToString() + lastRow1].NumberValue = result[1]; int tmad = 0; if (fileName1.Contains(fullpath1)) { readCSV(fullpath1, out DataTable dt1); if (AnalyzeCSV(dt1, "TMAD", "2004 | Vb", condition)[0] != 0) { sheet.Range[Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow1].NumberValue = AnalyzeCSV(dt1, "TMAD", "2004 | Vb", condition)[0]; } else { tmad = AnalyzeCSV(dt1, "TMAD", "Insider | Vb", condition)[0]; sheet.Range[Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow1].NumberValue = tmad; } } else { int lastRow2 = lastRow1 - 1; tmad = (int)sheet.Range[Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow2].NumberValue; sheet.Range[Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow1].NumberValue = tmad; } driverData.Add(date, new List <string>() { result[0].ToString(), result[1].ToString(), tmad.ToString() }); sheet.Range[Convert.ToChar('B' + (name.Length + 2)).ToString() + lastRow1].Value = "||"; sheet.Range[Convert.ToChar('B' + (name.Length + 3)).ToString() + lastRow1].Formula = "=SUM(" + Convert.ToChar('B' + 1).ToString() + lastRow1 + ":" + Convert.ToChar('B' + (name.Length)).ToString() + lastRow1 + ")" + "/" + Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow1; sheet.Range[Convert.ToChar('B' + (name.Length + 3)).ToString() + lastRow1].NumberFormat = "0.000%"; sheet.Range["B6:" + Convert.ToChar('B' + (name.Length + 4)).ToString() + lastRow1].HorizontalAlignment = HorizontalAlignType.Center; } } }
public FileResult GetPDF() { #region "GetSessionVariables" string logon_user = (string)Session["logon_user"]; long teamId, repId; int month, year; teamId = (long)Session["IS_Team"]; repId = (long)Session["IS_Rep"]; month = (int)Session["IS_Month"]; year = (int)Session["IS_Year"]; OSC_Team oSC_Team = db.Teams.Find(teamId); OSC_Representative oSC_Representative = db.Representatives.Find(repId); #endregion "GetSessionVariables" #region "WorkbookUsingClosedXML" string templateFileName = Server.MapPath("~/Templates/Template.xlsx"); XLWorkbook workbook = new XLWorkbook(templateFileName); string exportPath = Server.MapPath("~/Export"); string excelFileName = "IndividualScorecard_" + oSC_Representative.LastName + oSC_Representative.FirstName + "_" + month.ToString() + year.ToString() + "_" + logon_user + ".xlsx"; string pdfFileName = "IndividualScorecard_" + oSC_Representative.LastName + oSC_Representative.FirstName + "_" + month.ToString() + year.ToString() + "_" + logon_user + ".pdf"; string tempFileName = exportPath + "/" + excelFileName; string outputFileName = exportPath + "/" + pdfFileName; if (System.IO.File.Exists(tempFileName)) { System.IO.File.Delete(tempFileName); } workbook.SaveAs(tempFileName); IXLWorksheet worksheet = workbook.Worksheet("Scorecard"); IXLWorksheet worksheet2 = workbook.Worksheet("Workitems"); IXLWorksheet worksheet3 = workbook.Worksheet("NPT"); #region "Table" List <IndividualScorecard> list = new List <IndividualScorecard>(); list = af.GetIndividualScorecardFull(teamId, repId, month, year); int x = 2; int y = 29; IXLCell cell = worksheet.Cell(y, x); cell.SetValue("Attendance"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Overtime"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("NPT Hours"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Processing Time"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Total Transactions"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Rate of Production"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Processing Quality"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Total Utilization"); x += 1; cell = worksheet.Cell(29, x); cell.SetValue("Efficiency"); for (int i = 1; i <= list.Count; i++) { y += 1; x = 2; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualActivities.Attendance_Days.ToString()); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualActivities.Overtime_Hours.ToString()); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualNonProcessing.NPTHours.ToString()); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualBIProd.ProcessingHours.ToString()); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualBIProd.Count.ToString()); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].ProductivityRating.ToString() + "%"); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].individualBIQual.QualityRating.ToString() + "%"); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].TotalUtilization.ToString() + "%"); x += 1; cell = worksheet.Cell(y, x); cell.SetValue(list[i - 1].Efficiency.ToString() + "%"); } do { x += 1; worksheet.Column(x).Clear(); }while (x <= 23); #endregion "Table" #region "Highlights" IndividualScorecard ind = af.GetIndividualScorecard(teamId, repId, month, year); cell = worksheet.Cell("A47"); cell.SetValue(ind.Highlights); #endregion "Highlights" #region "Worktypes" List <IndividualWorkTypes> worktypes = af.GetIndividualWorkTypes(teamId, repId, month, year); y = 1; x = 1; IXLCell cell2 = worksheet2.Cell(y, x); for (int i = 1; i <= worktypes.Count; i++) { y += 1; x = 1; cell2 = worksheet2.Cell(y, x); cell2.SetValue(worktypes[i - 1].WorkType.ToString()); x += 1; cell2 = worksheet2.Cell(y, x); cell2.SetValue(((int)worktypes[i - 1].Count)); } do { y += 1; worksheet2.Row(y).Clear(); }while(y <= 200); #endregion "Worktypes" #region "NPT" List <PieList> npts = af.GetIndividualNPT(teamId, repId, month, year); y = 1; x = 1; IXLCell cell3 = worksheet3.Cell(y, x); for (int i = 1; i <= npts.Count; i++) { y += 1; x = 1; cell3 = worksheet3.Cell(y, x); cell3.SetValue(npts[i - 1].Category.ToString()); x += 1; cell3 = worksheet3.Cell(y, x); cell3.SetValue((double)npts[i - 1].TimeSpent); } do { y += 1; worksheet3.Row(y).Clear(); }while (y <= 200); #endregion "NPT" #region "SaveWorkBook"" workbook.SaveAs(tempFileName); #endregion "SaveWorkBook" #endregion "WorkbookUsingClosedXML" #region "UsingSpireXLS" sxl.Workbook swb = new sxl.Workbook(); swb.LoadFromFile(tempFileName); sxl.Worksheet sws1 = swb.Worksheets[0]; sxl.Worksheet sws2 = swb.Worksheets[1]; sxl.Worksheet sws3 = swb.Worksheets[2]; sws1.TextBoxes[0].Text = oSC_Team.TeamName + " Monthly Scorecard"; sws1.TextBoxes[1].Text = oSC_Representative.FirstName + " " + oSC_Representative.LastName; sws1.TextBoxes[2].Text = db.months.Where(m => m.Value == Convert.ToString((int)month)).First().Text + "-" + year.ToString(); sxl.Chart chart1 = sws1.Charts[0]; chart1.DataRange = sws2.Range[1, 1, sws2.Rows.Count(), 2]; sxl.Chart chart2 = sws1.Charts[1]; chart2.DataRange = sws3.Range[1, 1, sws3.Rows.Count(), 2]; swb.Save(); #endregion "UsingSpireXLS" #region "WorkbookUsingInterop" //remove this codes when 403 - 454 when closedXML can generate this to PDF xl.Application app = new xl.Application(); xl.Workbook wb = app.Workbooks.Open(tempFileName); #region "Cover" xl.Sheets xs = wb.Worksheets; xl.Worksheet ws = (xl.Worksheet)xs.get_Item("Scorecard"); xl.Worksheet ws2 = (xl.Worksheet)xs.get_Item("Workitems"); xl.Worksheet ws3 = (xl.Worksheet)xs.get_Item("NPT"); int txt_ctr = 1; foreach (xl.Shape shp in ws.Shapes) { if (shp.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox) { if (txt_ctr == 1) { shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = oSC_Team.TeamName + " Monthly Scorecard"; } else if (txt_ctr == 2) { shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = oSC_Representative.FirstName + " " + oSC_Representative.LastName; shp.ZOrder(MsoZOrderCmd.msoBringToFront); } else { shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = db.months.Where(m => m.Value == Convert.ToString((int)month)).First().Text + "-" + year.ToString(); shp.ZOrder(MsoZOrderCmd.msoBringToFront); } } txt_ctr += 1; } int cht_ctr = 1; foreach (xl.ChartObject cht in ws.ChartObjects()) { if (cht_ctr == 1) { xl.Range last = ws2.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing); xl.Range chartRange = ws2.get_Range("A1", last); cht.Chart.SetSourceData(chartRange); } else { xl.Range last = ws3.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing); xl.Range chartRange = ws3.get_Range("A1", last); cht.Chart.SetSourceData(chartRange); } cht_ctr += 1; } #endregion "Cover" wb.Save(); wb.ExportAsFixedFormat(xl.XlFixedFormatType.xlTypePDF, outputFileName, xl.XlFixedFormatQuality.xlQualityStandard); wb.Close(); app.Quit(); #endregion "WorkbookUsingInterop" #region "Return" byte[] fileBytes = System.IO.File.ReadAllBytes(outputFileName); string fileName = pdfFileName; return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName)); #endregion "Return" }
private void button7_Click(object sender, EventArgs e) { _PrintExcel.Workbook workbook = new _PrintExcel.Workbook(); workbook.LoadFromFile(filename); _PrintExcel.Worksheet sheet = workbook.Worksheets["printout"]; sheet.SaveToPdf(path + "Sizing Printout.pdf"); System.Diagnostics.Process.Start("explorer.exe", path + "Sizing Printout.pdf"); workbook.Dispose(); //PrintDialog dialog = new PrintDialog(); //dialog.AllowPrintToFile = true; //dialog.AllowCurrentPage = true; //dialog.AllowSomePages = true; //dialog.AllowSelection = true; //dialog.UseEXDialog = true; //dialog.PrinterSettings.Duplex = Duplex.Simplex; //dialog.PrinterSettings.PrintRange = PrintRange.SomePages; //workbook.PrintDialog = dialog; //PrintDocument pd = workbook.PrintDocument; //if (dialog.ShowDialog() == DialogResult.OK) //{ pd.Print(); } //Application excel = new Application(); //_Excel.Workbook workbook = excel.Workbooks.Open(filename, ReadOnly: false, Editable: true); //_Excel.Worksheet worksheet = workbook.Worksheets["printout"] as _Excel.Worksheet; //worksheet.PrintPreview(); //worksheet.PrintOut(From:1,To:2,Copies:1, Preview:true, Type.Missing, PrintToFile:true, Type.Missing, Type.Missing); //worksheet.PrintPreview(); //PrintDialog printDlg = new PrintDialog(); /*PrintDocument printDoc = new PrintDocument(); * printDoc.DocumentName = "Print Document"; * printDlg.Document = printDoc; * printDlg.AllowSelection = true; * printDlg.AllowSomePages = true; * if (printDlg.ShowDialog() == DialogResult.OK) printDoc.Print();*/ // worksheet.PrintOut( //1, 1, 1, Type.Missing, //Type.Missing, Type.Missing, Type.Missing, Type.Missing); // // Cleanup: // GC.Collect(); // GC.WaitForPendingFinalizers(); // Marshal.FinalReleaseComObject(worksheet); // workbook.Close(false, Type.Missing, Type.Missing); // Marshal.FinalReleaseComObject(workbook); // excel.Quit(); // Marshal.FinalReleaseComObject(excel); /*workbook.DisplayAlerts = false; * excel.ActiveWorkbook.Save(); * excel.Application.Quit(); * excel.Quit();*/ }
private void bt_baocao_Click(object sender, EventArgs e) { //Create a new workbook Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); //Initialize worksheet workbook.CreateEmptySheets(1); Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; string conString = @"Data Source=DESKTOP-RGHAECC;Initial Catalog=SucKhoeNhanVien_PNT;Integrated Security=True"; SqlConnection sqlCon = new SqlConnection(conString); sqlCon.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT LichSuBenh.Id_LichSuBenh,NhanVien.MaNV,NhanVien.TenNV,Khoa.TenKhoa,ChucVu.TenChucVu,LichSuBenh.NgayKham,LichSuBenh.PhanLoaiSK,LichSuBenh.BenhKhac from NhanVien, LichSuBenh, Khoa , ChucVu where NhanVien.IdNhanVien = LichSuBenh.IdNhanVien And NhanVien.Khoa = Khoa.IdKhoa And NhanVien.IdChucVu = ChucVu.IdChucVu", sqlCon); System.Data.DataTable dtMainSQLData = new System.Data.DataTable(); da.Fill(dtMainSQLData); DataColumnCollection dcCollection = dtMainSQLData.Columns; // Export Data into EXCEL Sheet Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ExcelApp.Application.Workbooks.Add(Type.Missing); ExcelApp.Columns.ColumnWidth = 20; //Create a new workbook // Spire.Xls.Workbook workbook = new Spire.Xls.Workbook(); //Initialize worksheet // workbook.CreateEmptySheets(1); //Spire.Xls.Worksheet sheet = workbook.Worksheets[0]; //Set sheet name sheet.Name = "Chart data"; //Set the grid lines invisible sheet.GridLinesVisible = false; //Create a chart Spire.Xls.Chart chart = sheet.Charts.Add(ExcelChartType.Pie3D); //Set region of chart data chart.DataRange = sheet.Range["B2:B5"]; chart.SeriesDataFromRange = false; //Set position of chart chart.LeftColumn = 1; chart.TopRow = 6; chart.RightColumn = 9; chart.BottomRow = 25; //Chart title chart.ChartTitle = "Sales by year"; chart.ChartTitleArea.IsBold = true; chart.ChartTitleArea.Size = 12; //Initialize the chart series Spire.Xls.Charts.ChartSerie cs = chart.Series[0]; //Chart Labels resource cs.CategoryLabels = sheet.Range["A2:A5"]; //Chart value resource cs.Values = sheet.Range["B2:B5"]; //Set the value visible in the chart cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; //Year sheet.Range["A1"].Value = "Year"; sheet.Range["A2"].Value = "2002"; sheet.Range["A3"].Value = "2003"; sheet.Range["A4"].Value = "2004"; sheet.Range["A5"].Value = "2005"; //Sales sheet.Range["B1"].Value = "Sales"; sheet.Range["B2"].NumberValue = 4000; sheet.Range["B3"].NumberValue = 6000; sheet.Range["B4"].NumberValue = 7000; sheet.Range["B5"].NumberValue = 8500; //Style sheet.Range["A1:B1"].Style.Font.IsBold = true; sheet.Range["A2:B2"].Style.KnownColor = ExcelColors.LightYellow; sheet.Range["A3:B3"].Style.KnownColor = ExcelColors.LightGreen1; sheet.Range["A4:B4"].Style.KnownColor = ExcelColors.LightOrange; sheet.Range["A5:B5"].Style.KnownColor = ExcelColors.LightTurquoise; //Border sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].Color = Color.FromArgb(0, 0, 128); sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin; sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.FromArgb(0, 0, 128); sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin; sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].Color = Color.FromArgb(0, 0, 128); sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin; sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].Color = Color.FromArgb(0, 0, 128); sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin; //Number format sheet.Range["B2:C5"].Style.NumberFormat = "\"$\"#,##0"; chart.PlotArea.Fill.Visible = false; //Save the file // workbook.SaveToFile("Sample.xls", ExcelVersion.Version97to2003); //Launch the file //System.Diagnostics.Process.Start("Sample.xls"); // ExcelApp.Cells.CopyFromRecordset(objRS); for (int i = 1; i < dtMainSQLData.Rows.Count + 2; i++) { for (int j = 1; j < dtMainSQLData.Columns.Count + 1; j++) { if (i == 1) { ExcelApp.Cells[i, j] = dcCollection[j - 1].ToString(); ExcelApp.Cells[i, j].Font.Bold = true; ExcelApp.Cells[i, j].HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; Microsoft.Office.Interop.Excel.Range formatRange; formatRange = ExcelApp.Cells[i, j]; formatRange.Interior.Color = System.Drawing. ColorTranslator.ToOle(System.Drawing.Color.CornflowerBlue); } else { ExcelApp.Cells[i, j] = dtMainSQLData.Rows[i - 2][j - 1].ToString(); } ExcelApp.Cells[i, j].HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; } } //Save the file workbook.SaveToFile("Sample.xls", ExcelVersion.Version97to2003); //Launch the file System.Diagnostics.Process.Start("Sample.xls"); ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\Oanh\\Desktop\\BaoCaoSK.xls"); ExcelApp.ActiveWorkbook.Saved = true; ExcelApp.Quit(); }