当前位置: 首页>>代码示例>>C#>>正文


C# Workbook.SaveAs方法代码示例

本文整理汇总了C#中Microsoft.Office.Interop.Excel.Workbook.SaveAs方法的典型用法代码示例。如果您正苦于以下问题:C# Workbook.SaveAs方法的具体用法?C# Workbook.SaveAs怎么用?C# Workbook.SaveAs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Office.Interop.Excel.Workbook的用法示例。


在下文中一共展示了Workbook.SaveAs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExpotToExcel

        public void ExpotToExcel(DataGridView dataGridView1,string SaveFilePath)
        {
            xlApp = new Excel.Application();
               xlWorkBook = xlApp.Workbooks.Add(misValue);
               xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
               int i = 0;
               int j = 0;

               for (i = 0; i <= dataGridView1.RowCount - 1; i++)
               {
               for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
               {
                   DataGridViewCell cell = dataGridView1[j, i];
                   xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
               }
               }

               xlWorkBook.SaveAs(SaveFilePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
               xlWorkBook.Close(true, misValue, misValue);
               xlApp.Quit();

               releaseObject(xlWorkSheet);
               releaseObject(xlWorkBook);
               releaseObject(xlApp);

               MessageBox.Show("Your file is saved" + SaveFilePath);
        }
开发者ID:MisuBeImp,项目名称:DhakaUniversityCyberCenterUserApps,代码行数:27,代码来源:CardUsageController.cs

示例2: reporttoexcel_turnover

        public void reporttoexcel_turnover(List<string> station_name_list, List<int> station_turnover_list, List<int> station_avg_list)
        {


            
            Eapp.Visible = true;

            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            book = Eapp.Workbooks.Open(path + @"\отчет_станций_шаблон.xlsx");

            excel.Worksheet sheet = (excel.Worksheet)book.Worksheets.get_Item(1);
           
            excel.Range range_sheet = sheet.UsedRange;

            for (int i = 2; i < station_name_list.Count + 2; i++)
            {

                excel.Range range_cur = range_sheet.Cells[i, 1];
                
                range_cur.Value2 = station_name_list[i - 2];

                range_cur = range_sheet.Cells[i, 2];
                range_cur.Value2 = station_turnover_list[i - 2];

                range_cur = range_sheet.Cells[i, 3];
                range_cur.Value2 = station_avg_list[i - 2];
               

            }
            
            book.SaveAs(path + @"\reports\отчет_станций.xlsx");
            Eapp.Quit();

        }
开发者ID:Alexanderexe,项目名称:course_Project,代码行数:34,代码来源:COM_out.cs

示例3: MakeExcelFile

        /// <summary>
        /// Сохраняем файлы в формате пдф и ексель в папки
        /// </summary>
        public void MakeExcelFile(decimal moneyAtStart, decimal moneyBalance)
        {
            string dateFile;    //Повна назва файлу для зберігання
            try
            {
                CreateFolderForSavingFile(excelFilePath, out dateFile);

                oApp = new Excel.Application();
                oBook = oApp.Workbooks.Add();
                oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);

                // Заповнюємо excel файл данними
                CreateFullFile();
                InputInformationFields(moneyAtStart, moneyBalance);

                // Зберігаємо файл в форматі екселя
                oBook.SaveAs(dateFile + ".xlsx");

                CreateFolderForSavingFile(pdfFilePath, out dateFile);

                // Додаткова перевірка при зберіганні pdf файла на встановлене розширення в Office
                try
                {
                    oBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, dateFile + ".pdf");
                }
                catch (ArgumentException)
                {
                    MessageBox.Show("Помилка при збереженні PDF файла. Перевірте чи у Вас встановлене розширення в "
                        + " Microsoft Office для збереження файлів в форматі PDF/XPS.", "Помилка при збереженні PDF",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }               
                catch (Exception)
                {
                    MessageBox.Show("Помилка при збереженні pdf файла.");
                }


                MessageBox.Show("Дані збережено!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
            finally
            {
                oBook.Close();
                oApp.Quit();
            }
        }
开发者ID:franko-vv,项目名称:Input-and-Outlay,代码行数:52,代码来源:CreateExcelFile.cs

示例4: WriteInExl

        //public Write2Exl()
        //{ 
        //}

        public void WriteInExl(List<string> workList)
        {
            xlApp = new Excel.Application(); // open Excel App
            xlWorkBookTar = xlApp.Application.Workbooks.Open(wrtFilePath); // open Workbook

            //wrtBySht("InstrumentClassData");
            foreach (string item in workList)
            {
                wrtBySht(item);
            }
            xlWorkBookTar.SaveAs(wrtFilePath, misValue, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue);
            xlWorkBookTar.Close();
            xlApp.Quit();
            finProg();
        }
开发者ID:Sho20,项目名称:In2S3D_v4,代码行数:19,代码来源:Write2Exl.cs

示例5: button1_Click

 private void button1_Click(object sender, EventArgs e)
 {
     var filepath = @"d:\dupa.xlsx";
     MyApp = new Excel.Application();
     MyApp.Visible = false;
     MyBook = MyApp.Workbooks.Open(filepath);
     MySheet = (Excel.Worksheet)MyBook.Sheets["Arkusz3"]; // Explicit cast is not required here
     Excel.Range cell = MySheet.Range[MySheet.Cells[1, 1], MySheet.Cells[4, 4]];
     foreach (Excel.Range item in cell)
     {
         item.Value = string.Format("row:{0:D2} col:{1:D2}", item.Row, item.Column);
     }
     MyBook.SaveAs(Filename: filepath);
     MyBook.Close();
 }
开发者ID:100nka,项目名称:WindowsFormsApplication5,代码行数:15,代码来源:Form1.cs

示例6: ExportToExcel

        public string ExportToExcel(DocumentModel document,string savePath)
        {
            savePath = savePath + Path.GetRandomFileName().Replace('.', 'a') + ".xlsx";
                myApp = new Excel.Application();
                myApp.Visible = false;
                myBook = myApp.Workbooks.Add();
                mySheet = (Excel.Worksheet)myBook.Sheets[1];
                var lastRow = mySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;

                WriteHeadTable(document.HeadTable, ref lastRow);
                WriteActs(document.Acts, ref lastRow);
                WriteTables(document.Tables, ref lastRow);

                mySheet.Columns.AutoFit();
                myBook.SaveAs(savePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                myBook.Close(false);
                myApp.Quit();
                return savePath;
        }
开发者ID:MalakhovVladislav,项目名称:practice,代码行数:19,代码来源:Exporter.cs

示例7: exportExcelv2


//.........这里部分代码省略.........
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 3], xlWorkSheet.Cells[1, 3]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 3], xlWorkSheet.Cells[1, 3]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 3] = "ม.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 4], xlWorkSheet.Cells[1, 4]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 4], xlWorkSheet.Cells[1, 4]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 4], xlWorkSheet.Cells[1, 4]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 4] = "ก.พ.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 5], xlWorkSheet.Cells[1, 5]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 5], xlWorkSheet.Cells[1, 5]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 5], xlWorkSheet.Cells[1, 5]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 5] = "มี.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 6], xlWorkSheet.Cells[1, 6]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 6], xlWorkSheet.Cells[1, 6]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 6], xlWorkSheet.Cells[1, 6]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 6] = "ม.ย.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 7], xlWorkSheet.Cells[1, 7]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 7], xlWorkSheet.Cells[1, 7]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 7], xlWorkSheet.Cells[1, 7]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 7] = "พ.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 8], xlWorkSheet.Cells[1, 8]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 8], xlWorkSheet.Cells[1, 8]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 8], xlWorkSheet.Cells[1, 8]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 8] = "มิ.ย.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 9], xlWorkSheet.Cells[1, 9]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 9], xlWorkSheet.Cells[1, 9]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 9], xlWorkSheet.Cells[1, 9]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 9] = "ก.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 10], xlWorkSheet.Cells[1, 10]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 10], xlWorkSheet.Cells[1, 10]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 10], xlWorkSheet.Cells[1, 10]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 10] = "ส.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 11], xlWorkSheet.Cells[1, 11]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 11], xlWorkSheet.Cells[1, 11]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 11], xlWorkSheet.Cells[1, 11]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 11] = "ก.ย.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 12], xlWorkSheet.Cells[1, 12]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 12], xlWorkSheet.Cells[1, 12]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 12], xlWorkSheet.Cells[1, 12]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 12] = "ต.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 13] = "พ.ย.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].EntireColumn.ColumnWidth = 12;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 14] = "ธ.ค.";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].EntireColumn.ColumnWidth = 15;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 15] = "รวม";

                for (int i = 0; i < dt_value.Rows.Count; i++)
                {
                    xlWorkSheet.Range[xlWorkSheet.Cells[i + 2, 3], xlWorkSheet.Cells[i + 2, 5]].NumberFormat = "#,##0.00";
                }

                //xlWorkSheet.Range[xlWorkSheet.Cells[1, (countSpan_shop * (j + 1)) + 2], xlWorkSheet.Cells[dt_shop.Rows.Count + 2, (countSpan_shop * (j + 1)) + 2]].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SkyBlue);

                for (int i = 0; i < dt_value.Rows.Count; i++)
                {
                    for (int j = 0; j < dt_value.Columns.Count; j++)
                    {
                        xlWorkSheet.Cells[i + 2, j + 1] = dt_value.Rows[i][j].ToString();
                    }
                }

                string fileName = String.Empty;
                SaveFileDialog saveFileExcel = new SaveFileDialog();
                saveFileExcel.FileName = "" + DBConnString.sDb + " สรุปมูลค่าการขายแต่ละเดือน(แยกตามสินค้า) ปี " + CmbYear.Text + " ";
                saveFileExcel.Filter = "Excel files (*.xls,*.xlsx)|*.xls*";
                saveFileExcel.FilterIndex = 2;
                saveFileExcel.RestoreDirectory = true;
                if (saveFileExcel.ShowDialog() == DialogResult.OK)
                {
                    fileName = saveFileExcel.FileName;
                    xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();
                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
                    this.Cursor = Cursors.Default;
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = Oldcul;
                this.Cursor = Cursors.Default;
            }
        }
开发者ID:itktc,项目名称:projectktc-v2,代码行数:101,代码来源:rptSummarySaleMonthProduct.cs

示例8: ExportExcel

        private void ExportExcel(string path)
        {
            bool success = false;
            object misValue = System.Reflection.Missing.Value;

            excelApp = new Microsoft.Office.Interop.Excel.Application();

            if (excelApp == null) {
                MessageBox.Show("Excel is not properly installed!!");
                return;
            }

            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress = true;

            PawnGuardDBDataContext pawnguard = new PawnGuardDBDataContext();
            ProgStackPanel.Visibility = System.Windows.Visibility.Visible;
            ProgTextCancel.Visibility = System.Windows.Visibility.Collapsed;
            ProgressGrid.Visibility = System.Windows.Visibility.Visible;
            StoneListGrid.Visibility = System.Windows.Visibility.Hidden;
            Import.IsEnabled = false;
            Export.IsEnabled = false;
            this.MinHeight = 500;
            ProgText.Text = "Exporting Data...";
            ProgressStone.Value = 0;

            worker.DoWork += delegate(object sdr, DoWorkEventArgs dw) {
                Excel.Application _excelApp = (Excel.Application)dw.Argument;
                xlWorkBook = _excelApp.Workbooks.Open(path);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                List<Stone> stones = pawnguard.Stones.ToList<Stone>();
                for (int row = 0; row < stones.Count; row++) {
                    for (int col = 0; col < 13; col++) {
                        if (col == 0)  xlWorkSheet.Cells[row + 2, col + 1] = stones[row].rarity;
                        if (col == 1) xlWorkSheet.Cells[row + 2, col + 1] = stones[row].name;
                        if (col == 2) xlWorkSheet.Cells[row + 2, col + 1] = stones[row].carat;
                        if (col == 3) xlWorkSheet.Cells[row + 2, col + 1] = stones[row].price;
                    }
                    worker.ReportProgress(Convert.ToInt32(((decimal)row / (decimal)stones.Count) * 100));
                    System.Threading.Thread.Sleep(100);

                    if (worker.CancellationPending) {
                        ProgText.Dispatcher.Invoke(new Action(() => { ProgText.Text = "Canceling..."; }));
                        System.Threading.Thread.Sleep(2000);
                        dw.Cancel = true;
                        return;
                    }
                }
            };

            worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) {
                ProgressStone.Value = args.ProgressPercentage;
            };

            worker.RunWorkerCompleted += delegate(object sdr, RunWorkerCompletedEventArgs rwc) {
                if (rwc.Error != null) {
                    MessageBox.Show(rwc.Error.Message);
                    return;
                }

                if (!rwc.Cancelled) {
                    ProgressStone.Value = 100;
                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.FileName = "Stone Template.xlsx";
                    dlg.DefaultExt = ".xlsx";
                    dlg.Filter = "Stone Template|*.xlsx";

                    Nullable<bool> result = dlg.ShowDialog();
                    if (result == true) {
                        string filename = dlg.FileName;
                        xlWorkBook.SaveAs(filename);
                        success = true;
                        path = filename;
                    }
                } else {
                    ProgText.Dispatcher.Invoke(new Action(() => { ProgText.Text = "Cancelled"; }));
                }

                xlWorkBook.Close(true, misValue, misValue);
                excelApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(excelApp);

                ProgressGrid.Visibility = System.Windows.Visibility.Hidden;
                StoneListGrid.Visibility = System.Windows.Visibility.Visible;
                Import.IsEnabled = true;
                Export.IsEnabled = true;
                this.MinHeight = 300;

                if (success) {
                    System.Diagnostics.Process.Start(path);
                }
            };

            worker.RunWorkerAsync(excelApp);
        }
开发者ID:Olegna,项目名称:PawnGuard,代码行数:100,代码来源:StonePage.xaml.cs

示例9: ExportToExcel_gp


//.........这里部分代码省略.........
                xlWorkSheet.Cells[1, 12] = "ราคาทุนรวม";

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].EntireColumn.ColumnWidth = 20;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 13], xlWorkSheet.Cells[1, 13]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 13] = "กำไร(ขาดทุน) รวม";

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].EntireColumn.ColumnWidth = 15;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 14], xlWorkSheet.Cells[1, 14]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 14] = "ชื่อผู้ขาย";

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].EntireColumn.ColumnWidth = 20;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 15], xlWorkSheet.Cells[1, 15]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 15] = "ชื่อลูกค้า";

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 16], xlWorkSheet.Cells[1, 16]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 16], xlWorkSheet.Cells[1, 16]].EntireColumn.ColumnWidth = 20;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 16], xlWorkSheet.Cells[1, 16]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 16] = gvGP.Columns[15].HeaderText;

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 17], xlWorkSheet.Cells[1, 17]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 17], xlWorkSheet.Cells[1, 17]].EntireColumn.ColumnWidth = 20;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 17], xlWorkSheet.Cells[1, 17]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 17] = gvGP.Columns[16].HeaderText;

                object[,] oo = new object[dt_gp.Rows.Count, dt_gp.Columns.Count];

                for (i = 0; i < dt_gp.Rows.Count; i++)
                {
                    for (int j = 0; j < dt_gp.Columns.Count; j++)
                    {
                        string value = "";
                        try
                        {
                            decimal num = 0;
                            DateTime dateTime = new DateTime();
                            value = dt_gp.Rows[i][j].ToString();
                            if (DateTime.TryParse(value, out dateTime) && !Decimal.TryParse(value, out num))
                            {
                                oo[i, j] = (dateTime).ToOADate();
                                //xlWorkSheet.Cells[i + 2, j + 1] = (dateTime).ToOADate();
                                //xlWorkSheet.get_Range("A" + (i + 2), "A" + (j + 1)).NumberFormat = "dd-mm-yyyy";
                                //xlWorkSheet.get_Range("A" + (i + 2), "A" + (j + 1)).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            }
                            else
                            {
                                oo[i, j] = dt_gp.Rows[i][j].ToString();
                                //xlWorkSheet.Cells[i + 2, j + 1] = dt_gp.Rows[i][j].ToString();
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                string excelRange = string.Format("A2:{0}{1}",
                findColumnLetter(dt_gp.Columns.Count), dt_gp.Rows.Count + 1);
                xlWorkSheet.get_Range(excelRange, Type.Missing).Value2 = oo;

                xlWorkSheet.get_Range("A2", "A" + dt_gp.Rows.Count + 1).NumberFormat = "dd-mm-yyyy";
                xlWorkSheet.get_Range("G2", "G" + dt_gp.Rows.Count + 1).NumberFormat = "#,##0.00";
                xlWorkSheet.get_Range("H2", "H" + dt_gp.Rows.Count + 1).NumberFormat = "#,##0.00";
                xlWorkSheet.get_Range("I2", "I" + dt_gp.Rows.Count + 1).NumberFormat = "#,##0.00";
                string fileName = String.Empty;
                SaveFileDialog saveFileExcel = new SaveFileDialog();
                saveFileExcel.FileName = "" + DBConnString.sDb + " GP ตั้งแต่วันที่ " + dateTimePicker1.Text + " ถึง " + dateTimePicker2.Text + " ";
                saveFileExcel.Filter = "Excel files (*.xls,*.xlsx)|*.xls*";
                saveFileExcel.FilterIndex = 2;
                saveFileExcel.RestoreDirectory = true;
                if (saveFileExcel.ShowDialog() == DialogResult.OK)
                {
                    fileName = saveFileExcel.FileName;
                    xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();
                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("Export " + saveFileExcel.FileName + " Complete.");
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = Oldcul;
                this.Cursor = Cursors.Default;
            }
        }
开发者ID:itktc,项目名称:projectktc-v2,代码行数:101,代码来源:GP_Control.cs

示例10: exportarExcel


//.........这里部分代码省略.........
                            }
                            i += 2;

                            hoja_maderable.Cells[i, 1] = "Lugar";
                            hoja_maderable.Cells[i, 2] = "Responsable";
                            hoja_maderable.Cells[i, 3] = "Coor X";
                            hoja_maderable.Cells[i, 4] = "Coor Y";
                            hoja_maderable.Cells[i, 5] = "Linea";
                            hoja_maderable.Cells[i, 6] = "Parcela";
                            hoja_maderable.Cells[i, 7] = "Estrato";

                            hoja_maderable.Cells[i, 8] = "Numero de arbol";
                            hoja_maderable.Cells[i, 9] = "Nombre comun";
                            hoja_maderable.Cells[i, 10] = "Nombre cientifico";
                            hoja_maderable.Cells[i, 11] = "Calidad";
                            hoja_maderable.Cells[i, 12] = "DAP";
                            hoja_maderable.Cells[i, 13] = "CAP";
                            hoja_maderable.Cells[i, 14] = "Altura comercial";
                            hoja_maderable.Cells[i, 15] = "Altura total";
                            hoja_maderable.Cells[i, 16] = "Area basal";
                            hoja_maderable.Cells[i, 17] = "Volumen comercial";
                            hoja_maderable.Cells[i, 18] = "Volumen total";

                            hoja_maderable.get_Range("A1", "O1").Font.Bold = true;
                            hoja_maderable.get_Range("A1", "O1").VerticalAlignment =
                                excel.XlVAlign.xlVAlignCenter;

                            i++;
                            foreach (FORMULARIO form in py.FORMULARIO)
                            {
                                bar.Maximum = form.LINEAINVENTARIO.Count;
                                bar.Value = 0;

                                hoja_maderable.Cells[i, 1] = py.LUGAR.ToString();
                                hoja_maderable.Cells[i, 2] = form.USUARIO.NOMBRES + form.USUARIO.APELLIDOS;

                                hoja_maderable.Cells[i, 3] = form.COORDENADAX;
                                hoja_maderable.Cells[i, 4] = form.COORDENADAY;
                                hoja_maderable.Cells[i, 5] = form.LINEA.ToString();
                                hoja_maderable.Cells[i, 6] = form.PARCELA.ToString();
                                if (form.ESTRATO != null)  hoja_maderable.Cells[i, 7] = form.ESTRATO.DESCRIPESTRATO.ToString();

                                foreach (LINEAINVENTARIO lineInv in form.LINEAINVENTARIO)
                                {
                                    data = true;
                                    hoja_maderable.Cells[i, 1] = py.LUGAR.ToString();
                                    hoja_maderable.Cells[i, 2] = form.USUARIO.NOMBRES + form.USUARIO.APELLIDOS;

                                    hoja_maderable.Cells[i, 3] = form.COORDENADAX.ToString();
                                    hoja_maderable.Cells[i, 4] = form.COORDENADAY.ToString();
                                    hoja_maderable.Cells[i, 5] = form.LINEA.ToString();
                                    hoja_maderable.Cells[i, 6] = form.PARCELA.ToString();
                                    if (form.ESTRATO != null)  hoja_maderable.Cells[i, 7] = form.ESTRATO.DESCRIPESTRATO.ToString();

                                    hoja_maderable.Cells[i, 8] = lineInv.NROARB.ToString();
                                    hoja_maderable.Cells[i, 9] = lineInv.ESPECIE.NOMCOMUN.ToString();
                                    hoja_maderable.Cells[i, 10] = lineInv.ESPECIE.NOMCIENTIFICO.ToString();
                                    hoja_maderable.Cells[i, 11] = lineInv.CALIDAD.CODCALIDAD.ToString();
                                    hoja_maderable.Cells[i, 12] = lineInv.DAP;
                                    hoja_maderable.Cells[i, 13] = lineInv.CAP;
                                    hoja_maderable.Cells[i, 14] = lineInv.ALTCOMER_M;
                                    hoja_maderable.Cells[i, 15] = lineInv.ALTTOT_M;
                                    hoja_maderable.Cells[i, 16] = lineInv.AREABASAL;
                                    hoja_maderable.Cells[i, 17] = lineInv.VOLCOM;
                                    hoja_maderable.Cells[i, 18] = lineInv.VOLTOT;
                                    i++;
                                    bar.Increment(1);
                                }
                                if (form.LINEAINVENTARIO.Count == 0) i++;

                            }
                            if(data)libros_trabajo.Worksheets.Add(hoja_maderable);
                            MessageBox.Show("Los datos se exportaron correctamente.", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            bar.Visible = false;
                            libros_trabajo.SaveAs(fichero.FileName,
                            excel.XlFileFormat.xlWorkbookNormal);
                            libros_trabajo.Close(true);
                            aplicacion.Quit();
                            System.Diagnostics.Process.Start(fichero.FileName);
                        }
                        bar.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        bar.Visible = false;
                        throw ex;
                    }
                }
                else MessageBox.Show("No existe un proyecto abierto dentro del sistema.", "Operacion invalida", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                bar.Visible = false;
                Error_Form errorForm = new Error_Form(ex.Message);
                ToolStrip menu = bar.GetCurrentParent();
                Principal_Form parent = (Principal_Form)menu.Parent;
                errorForm.MdiParent = (Form)parent;
                errorForm.Show();
            }
        }
开发者ID:victacora,项目名称:sifca,代码行数:101,代码来源:ImporExportExcel.cs

示例11: ReadHeader

        private void ReadHeader(string fileName)
        {
            try
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                _excelApp = new Excel.ApplicationClass();
                _excelBook = _excelApp.Workbooks.Open(fileName,
                                                      0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "",
                                                      true, false, 0, true, false, false);
                if (_excelBook.Sheets.Count == 0)
                {
                    ShowInvalidExcel();
                    CloseExcel();
                    System.Threading.Thread.CurrentThread.CurrentCulture = _oldCi;
                    return;

                }
                _excelSheet = TNSHelper.GetFirtVisbleSheet(_excelBook);
                var rangeName = ((Excel.Range)_excelSheet.Cells[1, 1]);
                var text = rangeName != null ? rangeName.Value2.ToString() : "";
                TenNguon.Text = text;
                if (TenNguon.Text != "")
                {
                    text = text.Substring(text.IndexOf(']') + 1);
                    var temp = text.Split('|');
                    if (temp.Length > 0)
                    {
                        Tartget.Text = temp[0].TrimStart(' ', '(').Trim();
                        var tg = DMTnsTarget.GetTargetByName(Tartget.Text);
                        SetTarget(tg.Id, tg.Name, tg.DiplayName);
                        if (temp.Length > 1)
                        {
                            ThiTruong.Text = temp[1].TrimEnd(')').Trim();
                            var tt = DMTnsThiTruong.GetThiTruongByName(ThiTruong.Text);
                            SetThiTruong(tt.Id, tt.Name, tt.DiplayName);
                        }
                    }
                }
                _excelSheet.Cells[RowHeader, ColChannel] = TNS_SALE_REV_SCR_CT.KENH_PHAT_NAME;
                _excelSheet.Cells[RowHeader, ColTimeline] = TNS_SALE_REV_SCR_CT.TIME_BAND;
                _excelSheet.Cells[RowHeader, ColAdvertiser] = TNS_SALE_REV_SCR_CT.ADVERTISER_NAME;
                _excelSheet.Cells[RowHeader, ColBrand] = TNS_SALE_REV_SCR_CT.BRAND_NAME;
                _excelSheet.Cells[RowHeader, ColSector] = TNS_SALE_REV_SCR_CT.SECTOR_NAME;
                _excelSheet.Cells[RowHeader, ColGroup] = TNS_SALE_REV_SCR_CT.GROUP_NAME;
                _excelSheet.Cells[RowHeader, ColAgency] = TNS_SALE_REV_SCR_CT.AGENCY_NAME;
                int currentDateCol = ColStartDate;
                _listDates = new List<DateTime?>();
                while (true)
                {
                    var endDateCell = TNSHelper.GetCell(_excelSheet, RowDate, currentDateCol);
                    if (endDateCell == null || endDateCell.Value2 == null || endDateCell.Value2.ToString() == "")
                        break;
                    var date = TNSHelper.GetDateValue(endDateCell.Value2);
                    var name = TNSHelper.GetSubFix(date);
                    _excelSheet.Cells[RowHeader, currentDateCol + ColCostInBand] = TNS_SALE_REV_SCR_CT.ALTERNATIVE_COST +
                        name;
                    _excelSheet.Cells[RowHeader, currentDateCol + ColGrpInBand] = TNS_SALE_REV_SCR_CT.GRP + name;
                    _excelSheet.Cells[RowHeader, currentDateCol + ColDiscountInBand] = TNS_SALE_REV_SCR_CT.DISCOUNT + name;
                    _excelSheet.Cells[RowHeader, currentDateCol + ColCppInBand] = TNS_SALE_REV_SCR_CT.CPP + name;
                    _excelSheet.Cells[RowHeader, currentDateCol + ColGrpPercentInBand] = TNS_SALE_REV_SCR_CT.GRP_PERCENT + name;
                    _listDates.Add(date);
                    currentDateCol += endDateCell.MergeArea.Count;
                }

                var startDate = _listDates.Count == 0 ? null : _listDates[0];
                var endDate = _listDates.Count == 0 ? null : _listDates[_listDates.Count - 1];
                if (startDate == null || endDate == null)
                {
                    ShowInvalidExcel();
                }
                else
                {
                    TuThang.Value = startDate.Value.Month;
                    TuNam.Value = startDate.Value.Year;
                    DenNam.Value = startDate.Value.Year;
                    DenThang.Value = endDate.Value.Month;
                }
                _sheeName = Guid.NewGuid().ToString().Substring(0, 5) + DateTime.Today.ToString("yyyyMMddhhmmss");
                _excelSheet.Name = _sheeName;
                for (int i = 1; i < RowHeader; i++)
                {
                    ((Excel.Range)_excelSheet.Cells[1, 1]).EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
                }
                Excel.XlFileFormat xlFormat = _excelBook.FileFormat;

                _filePath = AppUtil.GetTempFile(Path.GetExtension(fileName));
                _excelBook.SaveAs(_filePath, xlFormat, Type.Missing,
                                  Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
                                  true, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                _excelVersion = _excelApp.Version;
                CloseExcel();
                System.Threading.Thread.CurrentThread.CurrentCulture = _oldCi;
            }
            catch (Exception ex)
            {
                PLException.AddException(ex);
                ShowInvalidExcel();
                CloseExcel();
            }
        }
开发者ID:khanhdtn,项目名称:did-vlib-2011,代码行数:100,代码来源:FrmTNSSaleRevScr.cs

示例12: btnExcel_Click

        private void btnExcel_Click(object sender, EventArgs e)
        {
            if ( !timer1.Enabled )
                btnStart_Click(sender, e);
               object misValue = System.Reflection.Missing.Value;
                xlApp = new Excel.Application();
                xlApp.Visible = false;
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlFunction = xlApp.WorksheetFunction;

                xlWorkSheetData = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                xlWorkSheetData.Name = "Pendulum";
                xlWorkSheetData.Activate();

                xlWorkSheetData.Cells[1, 1] = "Constants used, mass: " + tbm.Text + ", gravity: " + tbG.Text + ", Spring Constant: " + tbk.Text + ", Length: " + tbH.Text;
                xlRng = xlWorkSheetData.get_Range("A1", "N1");
                xlRng.Select();
                xlRng.Merge();

                xlWorkSheetData.Cells[2, 1] = "Initial Values used, Intial X: " + tbXi.Text + ", Initial Y: " + tbYi.Text + ", Initial X Velocity: " + vx0.Text + ", Initial Y Velocity: " + vy0.Text;
                xlRng = xlWorkSheetData.get_Range("A2", "N2");
                xlRng.Select();
                xlRng.Merge();

                xlWorkSheetData.Cells[lastRowExcel, 1] = "t"; // changes these to whatever you want
                xlWorkSheetData.Cells[lastRowExcel, 2] = "X";
                xlWorkSheetData.Cells[lastRowExcel, 3] = "Y";
                xlWorkSheetData.Cells[lastRowExcel, 4] = "Vx";
                xlWorkSheetData.Cells[lastRowExcel, 5] = "Vy";
                lblTransfer.Visible = true;
                for (int i = 0; i < excelData.Count; i++)
                {
                    xlWorkSheetData.Cells[i + 4, 1] = (excelData[i].time / 1000.00).ToString();
                    xlWorkSheetData.Cells[i + 4, 2] = excelData[i].x.ToString();
                    xlWorkSheetData.Cells[i + 4, 3] = excelData[i].y.ToString();
                    xlWorkSheetData.Cells[i + 4, 4] = excelData[i].vx.ToString();
                    xlWorkSheetData.Cells[i + 4, 5] = excelData[i].vy.ToString();
                }
                lblTransfer.Visible = false;
                try //essaye le sauvegarde
                {

                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        //sauvegarde le classeur courant
                        xlWorkBook.SaveAs(saveFileDialog1.FileName,
                            Excel.XlFileFormat.xlWorkbookDefault, misValue,
                            misValue, misValue, misValue,
                            Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue,
                            misValue, misValue, misValue);
                        xlWorkBook.Close();
                    }

                }
                catch //en cas d'erreur affiche le message
                {
                    MessageBox.Show("Impossible de sauvegarder le fichier.", "Erreur de sauvegarde de fichier Excel", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
        }
开发者ID:harley1011,项目名称:Physics_Simulations-Winforms,代码行数:59,代码来源:Form1.cs

示例13: exportarExcelDiametricClass

        public void exportarExcelDiametricClass(ProgressBar bar, DataGridView data, string Type, int numCLass)
        {
            try
            {

                SaveFileDialog fichero = new SaveFileDialog();
                bar.Visible = true;
                ProjectBL pyBl = new ProjectBL(Program.ContextData);

                PROYECTO project = (PROYECTO)Program.Cache.Get("project");
                if (project != null)
                {
                    fichero.Filter = "Excel (*.xls)|*.xls";
                    fichero.FileName = "Reporte "+ Type+" clases diametricas "+ project.LUGAR + " "+ DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year;
                    if (fichero.ShowDialog() == DialogResult.OK)
                    {
                        //hacer visible la barra de progreso y fijar el valor maximo con el numero de registros a exportar
                        bar.Visible = true;

                        aplicacion = new excel.Application();
                        libros_trabajo = aplicacion.Workbooks.Add();

                        excel.Worksheet hoja_reporte;
                        hoja_reporte = (excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
                        hoja_reporte.Name = "Reporte Clases Diametricas";
                        hoja_reporte.Cells[1, 1] = "Informacion del proyecto";
                        hoja_reporte.Cells[1, 1].Font.Bold = true;
                        hoja_reporte.Range[hoja_reporte.Cells[1, 1], hoja_reporte.Cells[1, data.Columns.Count]].Merge();

                        hoja_reporte.Cells[2, 1] = "Lugar";
                        hoja_reporte.Cells[2, 1].Font.Bold = true;
                        hoja_reporte.Cells[2, 2] = project.LUGAR.ToString();
                        hoja_reporte.Cells[2, 2].HorizontalAlignment =Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                        hoja_reporte.Cells[2, 2].WrapText = true;

                        hoja_reporte.Cells[3, 1] = "Descripcion";
                        hoja_reporte.Cells[3, 1].Font.Bold = true;
                        hoja_reporte.Cells[3, 2] = project.DESCRIPCION.ToString();
                        hoja_reporte.Cells[3, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                        hoja_reporte.Cells[3, 2].WrapText = true;

                        hoja_reporte.Cells[4, 1] = "Responsable";
                        hoja_reporte.Cells[4, 1].Font.Bold = true;
                        hoja_reporte.Cells[4, 2] = project.USUARIO.NOMBRES.ToString() + " " + project.USUARIO.APELLIDOS.ToString();
                        hoja_reporte.Cells[4, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                        hoja_reporte.Cells[4, 2].WrapText = true;

                        hoja_reporte.Cells[5, 1] = "Reporte " + Type;
                        hoja_reporte.Cells[5, 1].Font.Bold = true;
                        hoja_reporte.Range[hoja_reporte.Cells[5, 1], hoja_reporte.Cells[5, data.Columns.Count]].Merge();

                        hoja_reporte.get_Range("A1", "O" + data.Columns.Count).HorizontalAlignment = excel.XlVAlign.xlVAlignCenter;
                        hoja_reporte.get_Range("A" + data.Rows.Count + 6, "O" + data.Columns.Count).HorizontalAlignment = excel.XlVAlign.xlVAlignCenter;
                        int col = 1;
                        foreach (DataGridViewColumn column in data.Columns)
                        {
                            hoja_reporte.Cells[6, col].NumberFormat = "@";
                            hoja_reporte.Cells[6, col] = column.HeaderText.ToString();
                            hoja_reporte.Cells[6, col].WrapText = true;
                            hoja_reporte.Cells[6, col].Font.Bold = true;
                            col++;
                        }
                        int i = 7;

                        bar.Minimum = 0;
                        bar.Maximum = data.Rows.Count;
                        foreach (DataGridViewRow row in data.Rows)
                        {
                            //de formulario extraer coord x y Y el estrato la linea numero de parcela y el usuario se puede hay que revisar muy bien esta parte
                            int j = 1;
                            foreach (DataGridViewTextBoxCell cell in row.Cells)
                            {
                                hoja_reporte.Cells[i, j].WrapText = true;
                                hoja_reporte.Cells[i, j] = cell.Value.ToString();
                                if (j <= (data.Columns.Count - (numCLass + 3)))
                                {
                                    hoja_reporte.Cells[i, j].Font.Bold = true;
                                }
                                j++;
                            }
                            bar.Increment(1);
                            i++;
                        }

                        libros_trabajo.Worksheets.Add(hoja_reporte);

                        MessageBox.Show("Los datos se exportaron correctamente.", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        bar.Visible = false;
                        libros_trabajo.SaveAs(fichero.FileName, excel.XlFileFormat.xlWorkbookNormal);
                        libros_trabajo.Close(true);
                        aplicacion.Quit();
                        System.Diagnostics.Process.Start(fichero.FileName);
                    }
                }
                else MessageBox.Show("No existe un proyecto abierto dentro del sistema.", "Operacion invalida", MessageBoxButtons.OK, MessageBoxIcon.Error);
                bar.Visible = false;
            }
            catch (Exception ex)
            {
                bar.Visible = false;
//.........这里部分代码省略.........
开发者ID:victacora,项目名称:sifca,代码行数:101,代码来源:ImporExportExcel.cs

示例14: exportExcelv2

        private void exportExcelv2()
        {
            if (dt_value.Rows.Count == 0) { MessageBox.Show("ไม่มีข้อมูล"); return; }
            var Oldcul = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat = Oldcul.DateTimeFormat;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                String[] Month = new String[] { "ม.ค.", "ก.พ.", "มี.ค", "เม.ย", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค.", "มูลค่ารวมแต่ละปี" };
                String[] Year = GetItemYear();
                int count = Year.Length;
                for (int i = 0; i < 13 * count; i++)
                {
                    int mod = i % count;
                    if (mod == 0)
                    {
                        xlWorkSheet.Cells[1, i + 3] = Month[i / count];
                    }
                    xlWorkSheet.Range[xlWorkSheet.Cells[2, i + 3], xlWorkSheet.Cells[2, i + 3]].Merge();
                    xlWorkSheet.Range[xlWorkSheet.Cells[2, i + 3], xlWorkSheet.Cells[2, i + 3]].EntireColumn.ColumnWidth = 12;
                    xlWorkSheet.Range[xlWorkSheet.Cells[2, i + 3], xlWorkSheet.Cells[2, i + 3]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    xlWorkSheet.Cells[2, i + 3] = Year[mod];
                }

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, (Month.Length * count)+2]].Font.Bold = true;

                xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].EntireColumn.ColumnWidth = 15;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].VerticalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 1] = "รหัสสินค้า";
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].Merge();
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].EntireColumn.ColumnWidth = 50;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].VerticalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Cells[1, 2] = "ชื่อสินค้า";

                for (int j = 3; j < (Month.Length * count) + 2; j+=count )
                {
                    xlWorkSheet.Range[xlWorkSheet.Cells[1, j], xlWorkSheet.Cells[1, j + count-1]].Merge();
                    xlWorkSheet.Range[xlWorkSheet.Cells[1, j], xlWorkSheet.Cells[1, j + count-1]].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                }

                object[,] oo = new object[dt_value.Rows.Count, dt_value.Columns.Count];

                for (int i = 0; i < dt_value.Rows.Count; i++)
                {
                    xlWorkSheet.Range[xlWorkSheet.Cells[i + 3, 3], xlWorkSheet.Cells[i + 3, dt_value.Columns.Count]].NumberFormat = "#,##0.00";
                }

                for (int i = 0; i < dt_value.Rows.Count; i++)
                {
                    for (int j = 0; j < dt_value.Columns.Count; j++)
                    {
                        oo[i, j] = dt_value.Rows[i][j].ToString();
                    }
                }

                string excelRange = string.Format("A3:{0}{1}",
                    findColumnLetter(dt_value.Columns.Count), dt_value.Rows.Count + 2);
                xlWorkSheet.get_Range(excelRange, Type.Missing).Value2 = oo;

                string fileName = String.Empty;
                SaveFileDialog saveFileExcel = new SaveFileDialog();
                saveFileExcel.FileName = "" + DBConnString.sDb + " สรุปมูลค่าการขายแต่ละปี " + TxtYear.Text + " ";
                saveFileExcel.Filter = "Excel files (*.xls,*.xlsx)|*.xls*";
                saveFileExcel.FilterIndex = 2;
                saveFileExcel.RestoreDirectory = true;
                if (saveFileExcel.ShowDialog() == DialogResult.OK)
                {
                    fileName = saveFileExcel.FileName;
                    xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();
                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("สำเร็จ");
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
//.........这里部分代码省略.........
开发者ID:itktc,项目名称:projectktc-v2,代码行数:101,代码来源:rptSummarySaleCompare.cs

示例15: ExportListViews2Excel

        //string idBill, string idUser, string idCustomer, DateTime time, long subtractMoney, long totalMoney)
        public static bool ExportListViews2Excel(string sSheetName, string sPath, List<ListView> lv)
        {
            try
            {
                // Khởi động chtr Excell
                exApp = new COMExcel.Application();

                // Thêm file temp xls
                exBook = exApp.Workbooks.Add(
                          COMExcel.XlWBATemplate.xlWBATWorksheet);

                // Lấy sheet 1.
                COMExcel.Worksheet exSheet = (COMExcel.Worksheet)exBook.Worksheets[1];

                exSheet.Activate();
                exSheet.Name = sSheetName;

                List<int> list_iMaxLength = new List<int>(); //Gia tri max de so sanh AutoFit column

                int iRowFit = 1;
                int iColumnFit = 1;
                bool isNewMaxLength = true;

                int rowIndex = 0;

                foreach (ListView listView in lv)
                {
                    int[] listOldMaxLength = new int[list_iMaxLength.Count];
                    list_iMaxLength.CopyTo(listOldMaxLength);
                    list_iMaxLength.Clear();

                    for (int iColumn = 0; iColumn < listView.Columns.Count; iColumn++)
                    {
                        COMExcel.Range r = (COMExcel.Range)exSheet.Cells[rowIndex + 1, iColumn + 1];

                        r.Font.Bold = true;
                        r.Value2 = listView.Columns[iColumn].Text.ToString();
                        //r.BorderAround(COMExcel.XlLineStyle.xlContinuous, COMExcel.XlBorderWeight.xlThin, COMExcel.XlColorIndex.xlColorIndexAutomatic, 1);

                        if (iColumn < listOldMaxLength.Length && listView.Columns[iColumn].Text.Length < listOldMaxLength[iColumn])
                        {
                            list_iMaxLength.Add(listOldMaxLength[iColumn]);
                        }
                        else
                        {
                            list_iMaxLength.Add(listView.Columns[iColumn].Text.Length);

                            COMExcel.Range rFit = (COMExcel.Range)exSheet.Cells[rowIndex + 1, iColumn + 1];
                            rFit.Columns.AutoFit();
                        }
                    }

                    //rowIndex += 1;

                    for (int iColumn = 0; iColumn < listView.Columns.Count; iColumn++)
                    {
                        iRowFit = rowIndex + 1;
                        iColumnFit = iColumn + 1;

                        for (int iRow = rowIndex; iRow < listView.Items.Count + rowIndex; iRow++)
                        {
                            COMExcel.Range r = (COMExcel.Range)exSheet.Cells[iRow + 2, iColumn + 1];

                            r.Value2 = listView.Items[iRow - rowIndex].SubItems[iColumn].Text.ToString();
                            //r.BorderAround(COMExcel.XlLineStyle.xlContinuous, COMExcel.XlBorderWeight.xlThin, COMExcel.XlColorIndex.xlColorIndexAutomatic, 1);

                            if (listView.Items[iRow - rowIndex].SubItems[iColumn].Text.Length > list_iMaxLength[iColumn])
                            {
                                list_iMaxLength[iColumn] = listView.Items[iRow - rowIndex].SubItems[iColumn].Text.Length;

                                iRowFit = iRow + 2;
                                iColumnFit = iColumn + 1;

                                isNewMaxLength = true;
                            }
                        }

                        if (isNewMaxLength)
                        {
                            COMExcel.Range rFit = (COMExcel.Range)exSheet.Cells[iRowFit, iColumnFit];
                            rFit.Columns.AutoFit();

                            isNewMaxLength = false;
                        }
                    }

                    rowIndex += listView.Items.Count;
                    rowIndex += 1;
                }

                exApp.Visible = false;

                exBook.SaveAs(sPath, COMExcel.XlFileFormat.xlWorkbookNormal,
                                null, null, false, false,
                                COMExcel.XlSaveAsAccessMode.xlExclusive,
                                false, false, false, false, false);
                exBook.Close(false, false, false);
                exApp.Quit();

//.........这里部分代码省略.........
开发者ID:vuchannguyen,项目名称:lg-py,代码行数:101,代码来源:Office_Function.cs


注:本文中的Microsoft.Office.Interop.Excel.Workbook.SaveAs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。