private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, " Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Cancelled)
            {
                //  cnnOLEDBx.Close();
                MessageBox.Show("Task Cancelled by User!", " Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                Excel1.DisplayAlerts = false;

                TotalError = sitenotexist;

                if (TotalError > 0)
                {
                    Worksheet1.Activate();
                    Excel.Range myRange;
                    myRange = Worksheet1.Range["A2", "Z" + Worksheet1.UsedRange.Rows.Count.ToString()];
                    myRange.Select();
                    myRange.Sort(Key1: myRange.Range["A2"], Order1: Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending, Orientation: Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns);

                    if (File.Exists(Path.GetDirectoryName(openFileDialog1.FileName).ToString() + @"\" + Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName).ToString() + " - Site Not Registered" + Path.GetExtension(openFileDialog1.FileName)))
                    {
                        File.Delete(Path.GetDirectoryName(openFileDialog1.FileName).ToString() + @"\" + Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName).ToString() + " - Site Not Registered" + Path.GetExtension(openFileDialog1.FileName));
                        Worksheet1.SaveAs(Path.GetDirectoryName(openFileDialog1.FileName).ToString() + @"\" + Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName).ToString() + " - Site Not Registered" + Path.GetExtension(openFileDialog1.FileName));
                    }
                    else
                    {
                        Worksheet1.SaveAs(Path.GetDirectoryName(openFileDialog1.FileName).ToString() + @"\" + Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName).ToString() + " - Site Not Registered" + Path.GetExtension(openFileDialog1.FileName));
                    }

                    MessageBox.Show("Cannot upload file.. \n\n" + "View error log saved in " + Path.GetDirectoryName(openFileDialog1.FileName).ToString() + ".", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    getMaxLineItems2();
                    Execute2();
                }
            }

            Workbook1.Close();

            Excel1.Quit();
            releaseObject(Excel1);
            releaseObject(Workbook1);
            releaseObject(Worksheet1);
        }
예제 #2
0
        public void exportexcelGA1(ref DataGridViewCommon dgv, string link, string filename, string model, string line, string dateFrom, string dateTo)
        {
            try
            {
                Excel.Application excelApp = new Excel.Application();
                excelApp.Workbooks.Add();
                Excel.Worksheet ws = excelApp.ActiveSheet;

                ws.Cells[1, 1] = "Model:"; ws.Cells[1, 2] = model;
                ws.Cells[1, 3] = "Line:"; ws.Cells[1, 4] = line;
                ws.Cells[2, 1] = "From;"; ws.Cells[2, 2] = dateFrom;
                ws.Cells[2, 3] = "To:"; ws.Cells[2, 4] = dateTo;
                // column headings
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    ws.Cells[4, (i + 1)] = dgv.Columns[i].HeaderText;
                }
                // rows

                for (int j = 0; j < dgv.Columns.Count; j++)
                {
                    for (int i = 0; i < dgv.Rows.Count; i++)
                    {
                        ws.Cells[(i + 5), (j + 1)] = dgv[j, i].Value.ToString();
                        if (i < dgv.RowCount - 1)
                        {
                            if (dgv.Rows[i].Cells["process"].Value.ToString() == dgv.Rows[i + 1].Cells["process"].Value.ToString())
                            {
                                ws.Range[ws.Cells[i + 5, 1], ws.Cells[i + 6, 1]].Merge();
                            }
                        }
                    }
                }
                excelApp.Visible = true;
                if (link.Length == 3)
                {
                    ws.SaveAs(link + filename + ".xlsx");
                }
                else
                {
                    ws.SaveAs(link + @"\" + filename + ".xlsx");
                }
            }
            catch
            {
                MessageBox.Show("ERROR. Please create folder " + link + " to save as...");
                return;
            }
        }
예제 #3
0
        private void button3_Click(object sender, EventArgs e)
        {
            string path = "";

            Microsoft.Office.Interop.Excel.Application exApp = new Microsoft.Office.Interop.Excel.Application();
            exApp.Workbooks.Add();
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)exApp.ActiveSheet;
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                workSheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
            }
            DateTime datevalue;

            for (int i = 0; i < dataGridView1.RowCount - 1; i++)
            {
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    if (DateTime.TryParse(dataGridView1.Rows[i].Cells[j].Value.ToString(), out datevalue) == false)
                    {
                        workSheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value;
                    }
                    else
                    {
                        workSheet.Cells[i + 2, j + 1] = Convert.ToDateTime(dataGridView1.Rows[i].Cells[j].Value).ToLongDateString();
                    }
                }
            }
            workSheet.Cells.ColumnWidth = 30;
            path = Environment.CurrentDirectory + "\\Excel.xlsx";
            workSheet.SaveAs(path);
            exApp.Quit();
            MessageBox.Show("Файл был сохранен в текущей рабочей папке!", "Успех!", MessageBoxButtons.OK);
        }
예제 #4
0
        protected void CreateExcelFile(string FileName, string sheetName, string[] colName)
        {
            //create
            object Nothing = System.Reflection.Missing.Value;
            var    app     = new Excel.Application();

            app.Visible = false;
            Excel.Workbook  workBook  = app.Workbooks.Add(Nothing);
            Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];
            worksheet.Name = sheetName;
            for (int i = 0; i < colName.Count(); i++)
            {
                worksheet.Cells[1, i + 1] = colName[i];
            }
            ////headline
            //worksheet.Cells[1, 1] = "日志ID";
            //worksheet.Cells[1, 2] = "内容";
            //worksheet.Cells[1, 3] = "类别";
            //worksheet.Cells[1,4] = "日志来源";
            //worksheet.Cells[1, 5] = "时间";

            worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
            workBook.Close(false, Type.Missing, Type.Missing);
            app.Quit();
        }
예제 #5
0
        public void exportexcel(ref DataGridViewCommon dgv, string link, string filename)
        {
            try
            {
                Excel.Application excelApp = new Excel.Application();
                excelApp.Workbooks.Add();
                Excel.Worksheet ws = excelApp.ActiveSheet;
                // column headings
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    ws.Cells[1, (i + 1)] = dgv.Columns[i].HeaderText;
                }
                // rows
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    for (int j = 0; j < dgv.Columns.Count; j++)
                    {
                        if (dgv[j, i].Value != null)
                        {
                            ws.Cells[(i + 2), (j + 1)] = dgv[j, i].Value.ToString();
                        }
                    }
                }
                excelApp.Visible = true;

                ws.SaveAs(link + @"\" + filename + ".xlsx");
            }
            catch
            {
                MessageBox.Show("ERROR. Please create folder " + link + " to save as...");
                return;
            }
        }
예제 #6
0
        public static void ExcelCOM(string[,] data, string savePath)
        {
            Excel.Application excelApp   = new Excel.Application();                    // Excel App 생성
            Excel.Workbook    workbook   = excelApp.Workbooks.Add(Type.Missing);       //sheet1 포함된 빈 워크북 생성
            Excel.Worksheet   worksheetA = workbook.Worksheets.Item["Sheet1"];         //sheet1 객체 가져오기
            Excel.Worksheet   worksheetB = workbook.Worksheets.Add(After: worksheetA); //sheet1 뒤에 새 워크시트 추가
            Excel.Range       range      = null;


            for (int i = 0; i < data.GetLength(0); i++)
            {
                worksheetA.Cells[i + 1, 1] = data[i, 0]; // Cells[열, 행], data[2차, 1차]
                worksheetA.Cells[i + 1, 2] = data[i, 1];
            }

            range         = worksheetB.Cells[1, 1]; //sheet2 | A1
            range.Formula = "Sheet2";               //sheet1 뒤 시트 | A1 기록

            range         = worksheetB.Cells[2, 1]; //sheet2 | A2
            range.Formula = "Sheet2";               //sheet1 뒤 시트 | A1 기록


            worksheetA.SaveAs(savePath + "\\shpark-book.xlsx"); // sheep1 저장
            excelApp.Quit();                                    //Excel App 종료
        }
예제 #7
0
        private void BtnToExcel_Click(object sender, RoutedEventArgs e)
        {
            Excel.Application excel = new Excel.Application();
            excel.Visible = true;
            excel.Workbooks.Add();
            Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
            worksheet.Cells[1, 1] = "№";
            worksheet.Cells[1, 2] = "Товар";
            worksheet.Cells[1, 3] = "Количиство";
            worksheet.Cells[1, 4] = "Цена";
            worksheet.Cells[1, 5] = "Сумма";
            int row = 2;

            for (int i = 0; i < orders.Count; i++, row++)
            {
                worksheet.Cells[row, 1] = orders[i].ID;
                worksheet.Cells[row, 2] = orders[i].Product;
                worksheet.Cells[row, 3] = orders[i].Quantity;
                worksheet.Cells[row, 4] = orders[i].Price;
                worksheet.Cells[row, 5] = orders[i].Sum;
            }
            row++;
            Excel.Range range = worksheet.get_Range(string.Format("D" + row), string.Format("E" + row)).Cells;
            range.Merge(Type.Missing);
            worksheet.Cells[row, 4] = "Итого: " + total;
            worksheet.Columns.AutoFit();
            worksheet.SaveAs(@"C:\Users\Koss4ok\Desktop\MyExcel");
            excel.Quit();
        }
        //
        //// Supprimer typologie dans "D:\\ptw\\Histo.ptw"
        //
        private void renommer()
        {
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            object            misValue = System.Reflection.Missing.Value;

            //missing values, for example, when you invoke methods that have default parameter values.
            //remplace les paramètres par default des fonctions utilisés

            xlApp         = new Excel.ApplicationClass();
            xlApp.Visible = true;
            xlWorkBook    = xlApp.Workbooks.Open(fichierprepare, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, true, false);
            //Afficher pas les Alerts !!non utiliser avant assurer!!!
            xlApp.DisplayAlerts = false;

            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Historique");
            //Excel.Worksheet sheetTypologie = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Typologie IFRS");
            //sheetTypologie.Delete();

            xlWorkSheet.SaveAs(prefaceNP, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet); //kill WorkSheet
            releaseObject(xlWorkBook);  //Kill WorkBook
            releaseObject(xlApp);       //Kill Application Application
        }
예제 #9
0
 private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     saveFileDialog1.Title  = "附和水准计算保存";
     saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|Excel数据文件(*.xls)|*.xls|Excel表格(*.xlsx)|*.xlsx";
     if (saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         #region TXT文档保存
         if (saveFileDialog1.FilterIndex == 1)
         {
             StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
             sw.WriteLine("附合水准平差计算\n");
             Class1.daochu1(sw, dataGridView4);
             sw.WriteLine("高程配赋平差计算\n");
             Class1.daochu1(sw, dataGridView3);
             sw.Flush();
             MessageBox.Show("保存成功!");
         }
         #endregion
         #region Excel文档保存
         else
         {
             Excel.Application excel1     = new Excel.Application();           //创建一个excel对象
             Excel.Workbook    workbook1  = excel1.Workbooks.Add(true);        //为该excel对象添加一个工作簿
             Excel.Worksheet   worksheet1 = excel1.Workbooks[1].Worksheets[1]; //获取工作簿中的第一个工作表
             Class1.daochu2(1, worksheet1, dataGridView4);
             Class1.daochu2(dataGridView2.Rows.Count + 2, worksheet1, dataGridView3);
             worksheet1.SaveAs(saveFileDialog1.FileName);//保存工作表
             workbook1.Close();
             MessageBox.Show("保存成功!");
         }
         #endregion
     }
 }
        private void ExportToExcel()
        {
            Excel.Application exApp = new Excel.Application();
            //exApp.Visible = true;
            exApp.Workbooks.Open(Environment.CurrentDirectory + @"\Шаблон.xls");
            Excel.Worksheet workSheet = (Excel.Worksheet)exApp.ActiveSheet;
            workSheet.Cells[1, 1] = "Cпеціальність " + comboBox1.Text;
            workSheet.Cells[2, 1] = "#";
            workSheet.Cells[2, 2] = "ПІБ";
            workSheet.Cells[2, 3] = "Дата народження";
            workSheet.Cells[2, 4] = "Пільги";
            workSheet.Cells[2, 5] = "Номер телефону";
            workSheet.Cells[2, 6] = "Рейтигновий бал вступу";
            workSheet.Cells[2, 7] = "Тип вступу";
            int rowExcel = 3;
            int y = 1, counter = 1;

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                workSheet.Cells[rowExcel, "A"] = counter.ToString();
                workSheet.Cells[rowExcel, "B"] = dataGridView1.Rows[i].Cells["ПІБ"].Value;
                workSheet.Cells[rowExcel, "C"] = dataGridView1.Rows[i].Cells["Дата_народження"].Value;
                workSheet.Cells[rowExcel, "D"] = dataGridView1.Rows[i].Cells["Пільги"].Value;
                workSheet.Cells[rowExcel, "E"] = dataGridView1.Rows[i].Cells["Номер_телефону"].Value;
                workSheet.Cells[rowExcel, "F"] = dataGridView1.Rows[i].Cells["Рейтигновий_бал_вступу"].Value;
                workSheet.Cells[rowExcel, "G"] = dataGridView1.Rows[i].Cells["Тип_вступу"].Value;

                ++rowExcel;
                ++counter;
            }
            workSheet.SaveAs("Вступники на спеціальність " + comboBox1.Text + ".xls");
            exApp.Quit();
            MessageBox.Show("Файл був збережений в папці 'Мої документи' під назвою 'Вступники на спеціальність " + comboBox1.Text + ".xls'", "Інформація", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #11
0
        /// <summary>
        /// 在制定的文件夹创建Excel文件
        /// </summary>
        static ExcelInterop()
        {
            app         = new Excel.Application();
            app.Visible = false;
            Excel.Worksheet worksheet = null;
            string          fileName  = Constants.CurrentDirectory + '\\' + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xlsx";

            if (System.IO.File.Exists(fileName))
            {
                workBook  = app.Workbooks.Open(fileName);
                worksheet = (Excel.Worksheet)workBook.Sheets[1];
                itemIdx   = worksheet.UsedRange.Rows.Count + 1;
                return;
            }

            object Nothing   = System.Reflection.Missing.Value;
            string childName = "Data Info";

            workBook       = app.Workbooks.Add(Nothing);
            worksheet      = (Excel.Worksheet)workBook.Sheets[1];
            worksheet.Name = childName;
            itemIdx        = 2;

            string[] headItems = { "时间", "ID编号", "ID号", "X坐标", "Y坐标" };
            int      idx       = 1;

            foreach (string strItem in headItems)
            {
                worksheet.Cells[1, idx++] = strItem;
            }

            worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        }
예제 #12
0
        //---> 'mergeRecords_Click'

        /* Activates the main and final segment of this program. Will only run if valid workforce and master
         * record files have been loaded and passed all checks. There are two main parts to this function:
         * 1) a call to the 'copyRecords' function, passing in the current master and workforce Excel
         *    worksheets and the row number where records for the current year begin (description of function
         *    is at function declaration)
         * 2) a call to the 'parseNumbers' function, passing just the current master record file
         *    (description of function is at function declaration) */
        private void mergeRecords_Click(object sender, EventArgs e)
        {
            //pointers for shorter names
            Excel.Worksheet currentMaster    = masterSheets.get_Item(this.masterTabName());
            Excel.Worksheet currentWorkforce = workforceSheets.get_Item(DateTime.Now.Year.ToString());

            //this.copyRecords(currentMaster, currentWorkforce, this.masterStartPoint(currentMaster));
            //this.parseNumbers(currentMaster);
            currentMaster.SaveAs("C:\\Users\\Jumbo\\Desktop\\Master " + DateTime.Now.Millisecond + ".xlsx",
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing,
                                 Type.Missing);
            //update location and progress tracker
            this.programLocation.Text = "Done";
            this.progress.Text        = String.Empty;
            //kill final processes
            this.killWorkforce();
            this.killMaster();
        }
예제 #13
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            string fileName     = Application.StartupPath + "\\" + "op13" + ".xlsx",
                   fileName_new = Application.StartupPath + "\\" + "time_op13_new" + ".xlsx";

            Excel.Application exApp = new Excel.Application();
            //Получаем набор ссылок на объекты Workbook
            Excel.Workbook excelappworkbooks = exApp.Workbooks.Open(fileName,
                                                                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                                    Type.Missing, Type.Missing);

            // Получить первый рабочий лист.
            Excel.Worksheet excelsheets = (Excel.Worksheet)excelappworkbooks.Sheets[1];

            //заполняем строку
            excelsheets.Cells[49, "P"]  = comboBoxMade.Text;
            excelsheets.Cells[49, "AH"] = textBoxMade.Text;
            excelsheets.Cells[13, "AR"] = comboBoxApproved.Text;
            excelsheets.Cells[15, "AS"] = textBoxApproved.Text;
            excelsheets.Cells[51, "P"]  = textBoxAccountant.Text;

            //Save to file
            excelsheets.SaveAs(fileName_new);

            exApp.Quit();
            this.Close();
        }
예제 #14
0
        public static void ExportToExcel <T>(List <T> data)
        {
            // Create Excell application
            Exc.Application excApp = new Exc.Application();

            // Create empty excel workbook
            excApp.Workbooks.Add();

            // Identify worksheet
            Exc.Worksheet worksheet = excApp.ActiveSheet;

            // Identify column headings
            worksheet.Cells[1, "A"] = "COLOR";
            worksheet.Cells[1, "B"] = "BRAND";

            // Insert Car List data into excel cells
            int row = 2;

            foreach (var item in data as List <Car> )
            {
                worksheet.Cells[row, "A"] = item.Color;
                worksheet.Cells[row, "B"] = item.Brand;
                row++;
            }

            worksheet.SaveAs($@"{Environment.CurrentDirectory}\Garage.xlsx");
            excApp.Quit();

            Console.WriteLine($"The garage list has been saved under this directory: {Environment.CurrentDirectory }");
        }
예제 #15
0
        static void Main(string[] args)
        {
            Excel.Application xlApp      = null;
            Excel.Workbook    xlWorkBook = null;

            xlApp      = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add();
            Excel.Worksheet newWorksheet = null;
            newWorksheet         = (Excel.Worksheet)xlApp.Application.Worksheets.Add();
            xlApp.ScreenUpdating = false;
            Excel.Range excelRange = newWorksheet.UsedRange;

            // Column 1
            excelRange.Cells.set_Item(1, 1, "Column 1");

            // Column 1 Data
            excelRange.Cells.set_Item(2, 1, "sss");

            // Column 2
            excelRange.Cells.set_Item(1, 2, "Column 2");

            // Column 1 Data
            excelRange.Cells.set_Item(2, 2, "ttt");


            // Save it as .xls
            newWorksheet.SaveAs("D:\\ExcelInterop", Excel.XlFileFormat.xlExcel7);

            // Clean up
            xlWorkBook.Close();
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
        }
예제 #16
0
파일: Form1.cs 프로젝트: Partunaks/Renault
 private void Accept_Click(object sender, EventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Excel.Range range = ObjWorkSheet1.get_Range("E:E").Find(PCName2.Text);
         ObjWorkSheet1.get_Range("D" + range.Row.ToString()).Value2 = SerialNum2.Text;
         ObjWorkSheet1.get_Range("C" + range.Row.ToString()).Value2 = PCModel2.Text;
         ObjWorkSheet1.get_Range("L" + range.Row.ToString()).Value2 = IPN2.Text;
         ObjWorkSheet1.get_Range("O" + range.Row.ToString()).Value2 = BuildingBox.Text;
         ObjWorkSheet1.get_Range("P" + range.Row.ToString()).Value  = Room.Text;
         ObjWorkSheet1.get_Range("K" + range.Row.ToString()).Value  = StatusBox.Text;
         ObjWorkSheet1.SaveAs(file);
         clear();
         MessageBox.Show("Файл успешно сохранен!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
         PCName2.Text     = "";
         PCModel2.Text    = "";
         SerialNum2.Text  = "";
         BuildingBox.Text = "";
         IPN2.Text        = "";
         Room.Text        = "";
         StatusBox.Text   = "";
         clear();
         Accept.Enabled = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex + "\n" + "Невозможно сохранить файл");
     }
 }
예제 #17
0
        public void DrawFunction()
        {
            List <USModel> mylist = new List <USModel>();

            mylist = Reader.ReadToEndTheCases(dataset_path, "Gwinnett").Difference();

            List <int> data = new List <int>(mylist.Count);

            int[] date = new int[mylist.Count];

            for (int i = 0; i < mylist.Count; i++)
            {
                data.Add(mylist[i].Cases);
                date[i] = i + 1;
            }
            data.ToArray();

            excel               = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible       = false;
            excel.DisplayAlerts = false;
            worKbooK            = excel.Workbooks.Add(Type.Missing);
            worKsheeT           = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet;
            worKsheeT.Name      = "DataForDraw";

            for (var i = 0; i < data.Count; i++)
            {
                worKsheeT.Cells[i + 1, 1] = data[i];
                worKsheeT.Cells[i + 1, 2] = date[i];
            }
            worKsheeT.SaveAs(excel_path);
            excel.Quit();
            Console.WriteLine(excel.Name);
        }
예제 #18
0
        static void Oldway(string[,] data, string savePath)//COM(Component Object Model - 마이크로소프트 사의 소프트웨어 컴포넌트 규격)을 이용하여 엑셀에 접근하기
        {
            Excel.Application excelApp = new Excel.Application();

            excelApp.Workbooks.Add(Type.Missing);

            Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet;

            for (int i = 0; i < data.GetLength(0); i++)
            {
                ((Excel.Range)worksheet.Cells[i + 1, 1]).Value2 = data[i, 0];
                ((Excel.Range)worksheet.Cells[i + 1, 2]).Value2 = data[i, 1];
            }

            worksheet.SaveAs(savePath + "\\shjang-book-old.xlsx",
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing
                             );

            excelApp.Quit();
        }
        /// <summary>
        /// Toma una plantilla de Excel y una serie de cambios a
        /// realizar sobre dicho documento y genera un archivo nuevo
        /// con las modificionesespecificadas.
        /// </summary>
        /// <param name="rutaFinal">Ruta donde se almacenará el archivo
        /// generado</param>
        /// <param name="rutaPlantilla">Ruta donde se encuentra la plantilla
        /// a usar</param>
        /// <param name="listaDatos">Lista de cambios a realizar sobre las
        /// celdas de la plantilla</param>
        /// <returns>Retorna un booleano que indica si la creación se realizó
        /// con éxito.</returns>
        public static bool LlenarPlantillaConDatos(String rutaFinal, String rutaPlantilla, List <DatoCelda> listaDatos)
        {
            // Iniciar Excel
            Excel.Application excel = new Excel.Application();

            try
            {
                // Cargar la plantilla de Excel
                Excel.Workbook  book  = excel.Workbooks.Open(rutaPlantilla);
                Excel.Worksheet sheet = excel.ActiveSheet as Excel.Worksheet;

                // Carga de datos al archivo
                foreach (DatoCelda dc in listaDatos)
                {
                    sheet.Cells[dc.Fila, dc.Columna] = dc.Valor;
                }

                sheet.SaveAs(rutaFinal);
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
            finally
            {
                excel.Quit();
            }
        }
예제 #20
0
파일: Host.cs 프로젝트: Aleffine/USBMonitor
        private void CreateExcelFile(string FileName)
        {
            //create
            object Nothing = System.Reflection.Missing.Value;

            Excel.Application app = null;
            app         = new Excel.Application();
            app.Visible = false;
            Excel.Workbook  workBook  = app.Workbooks.Add(Nothing);
            Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];
            Excel.Range     range     = (Excel.Range)worksheet.get_Range("A1", "E1");
            range.Font.Size           = 15;
            range.Font.Name           = "黑体";
            worksheet.Name            = "record";
            range.ColumnWidth         = 25;
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.Borders.LineStyle   = Excel.XlLineStyle.xlContinuous;
            //headline
            worksheet.Cells[1, 1] = "设备名称";
            worksheet.Cells[1, 2] = "发生时间";
            worksheet.Cells[1, 3] = "设备序列号";
            worksheet.Cells[1, 4] = "操作类型";
            worksheet.Cells[1, 5] = "操作人";

            worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
            workBook.Close(false, Type.Missing, Type.Missing);
            app.Quit();
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            excel.Application app = new excel.Application();
            excel.Worksheet   ws  = app.Workbooks.Add(Type.Missing).Sheets[1];

            ws.Cells[1, 1].Value        = "Date";
            ws.Cells[1, 2].Value        = "Team(Away)";
            ws.Cells[1, 3].Value        = "Team(Home)";
            ws.Cells[1, 4].Value        = "Time";
            ws.Cells[1, 5].Value        = "Location";
            ws.Cells[1, 6].Value        = "Finished";
            ws.Range["A1:F1"].Font.Bold = true;

            for (int i = 2; i < dgvRegularSeason.Rows.Count; i++)
            {
                ws.Cells[i, 1].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[0].Value);
                ws.Cells[i, 2].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[1].Value);
                ws.Cells[i, 3].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[2].Value);
                ws.Cells[i, 4].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[3].Value);
                ws.Cells[i, 5].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[4].Value);
                ws.Cells[i, 6].Value = Convert.ToString(dgvRegularSeason.Rows[i - 2].Cells[5].Value);
            }
            ws.Columns.AutoFit();
            ws.SaveAs(AppDomain.CurrentDomain.BaseDirectory + @"export.xlsx");
            app.Quit();
            Marshal.ReleaseComObject(ws);
            Marshal.ReleaseComObject(app);
            MessageBox.Show("Your file is export on the path " + AppDomain.CurrentDomain.BaseDirectory + @"export.xlsx");
        }
예제 #22
0
        public static void OldWay(string[,] data, string savePath)
        {
            Excel.Application excelApp = new Excel.Application();

            excelApp.Workbooks.Add(Type.Missing);

            Excel.Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

            for (int i = 0; i < data.GetLength(0); i++)
            {
                ((Excel.Range)workSheet.Cells[i + 1, 1]).Value2 = data[i, 0];
                ((Excel.Range)workSheet.Cells[i + 1, 2]).Value2 = data[i, 1];
            }

            workSheet.SaveAs(savePath + "\\shpark-book-old.xlsx",
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing,
                             Type.Missing);

            excelApp.Quit();
        }
예제 #23
0
        public string ExportPositions(IEnumerable <PositionsController.PositionExportViewModel> data, string filename)
        {
            var path = Path.Combine(HttpContext.Current.Server.MapPath(uploadDirPosition)) + "\\" + filename + ".xlsx";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            Excel.Application xlAppToExport = new Excel.Application();
            xlAppToExport.Workbooks.Add("");

            // ADD A WORKSHEET.
            Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet);
            xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"];

            // ROW ID FROM WHERE THE DATA STARTS SHOWING.
            int iRowCnt = 8;

            // SHOW THE HEADER.
            xlWorkSheetToExport.Cells[1, 1] = "Position Details";

            Excel.Range range = xlWorkSheetToExport.Cells[1, 1] as Excel.Range;
            range.EntireRow.Font.Name = "Calibri";
            range.EntireRow.Font.Bold = true;
            range.EntireRow.Font.Size = 20;

            xlWorkSheetToExport.Range["A1:D1"].MergeCells = true;       // MERGE CELLS OF THE HEADER.

            // SHOW COLUMNS ON THE TOP.
            xlWorkSheetToExport.Cells[iRowCnt - 1, 1] = "Name";
            xlWorkSheetToExport.Cells[iRowCnt - 1, 2] = "Description";
            xlWorkSheetToExport.Cells[iRowCnt - 1, 3] = "Level of experience";
            xlWorkSheetToExport.Cells[iRowCnt - 1, 4] = "Technology";
            xlWorkSheetToExport.Cells[iRowCnt - 1, 5] = "Employees assigned";



            int i;

            for (i = 0; i <= data.Count() - 1; i++)
            {
                xlWorkSheetToExport.Cells[iRowCnt, 1] = data.ElementAt(i).Name;
                xlWorkSheetToExport.Cells[iRowCnt, 2] = data.ElementAt(i).Description;
                xlWorkSheetToExport.Cells[iRowCnt, 3] = data.ElementAt(i).LevelOfExperience;
                xlWorkSheetToExport.Cells[iRowCnt, 4] = data.ElementAt(i).Technology;
                xlWorkSheetToExport.Cells[iRowCnt, 5] = data.ElementAt(i).Employees;


                iRowCnt = iRowCnt + 1;
            }

            // SAVE THE FILE IN A FOLDER.
            xlWorkSheetToExport.SaveAs(path);

            // CLEAR.
            xlAppToExport.Workbooks.Close();
            xlAppToExport.Quit();
            xlAppToExport = null;
            return(path);
        }
예제 #24
0
        public void saveExcel()
        {
            try
            {
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string path1       = System.IO.Path.Combine(desktopPath, "강의자료.xlsx");

                excelApp = new Excel.Application();
                excelApp.DisplayAlerts = false;
                workBook  = excelApp.Workbooks.Add();
                workSheet = workBook.Worksheets.get_Item(1) as Excel.Worksheet;

                workSheet.Cells[1, 1] = "강의명";
                workSheet.Cells[1, 2] = "제 목";
                workSheet.Cells[1, 3] = "작성일";

                for (int i = 0; i < VM.getCount1(); i++)
                {
                    workSheet.Cells[2 + i, 1] = VM.getList1().ElementAt(i).LmsSubject;
                    workSheet.Cells[2 + i, 2] = VM.getList1().ElementAt(i).LmsTitle;
                    workSheet.Cells[2 + i, 3] = VM.getList1().ElementAt(i).LmsRdate;
                }
                workSheet.Columns.AutoFit();
                workSheet.SaveAs(path1, Excel.XlFileFormat.xlWorkbookDefault);
                workBook.Close(true);
                excelApp.Quit();
            }
            finally
            {
                ReleaseObject(workSheet);
                ReleaseObject(workBook);
                ReleaseObject(excelApp);
            }
        }
예제 #25
0
파일: Excel.cs 프로젝트: wwkkww1983/LeProj
        public static void CreateExcelFile(string fileName, string sheetName, string[] title, int[] content)
        {
            //删除原来数据
            string filePath = "/Statis/" + fileName + ".xlsx";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            object Nothing = System.Reflection.Missing.Value;

            OfficeExcel.Application excel    = new OfficeExcel.Application();
            OfficeExcel.Workbook    workBook = excel.Workbooks.Add(Nothing);

            OfficeExcel.Worksheet worksheet = (OfficeExcel.Worksheet)workBook.Sheets.Add();
            worksheet.Name = sheetName;
            int idx = 1;

            foreach (string item in title)
            {
                worksheet.Cells[1, idx++] = item;
            }
            idx = 1;
            foreach (int item in content)
            {
                worksheet.Cells[2, idx++] = item;
            }
            worksheet.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, OfficeExcel.XlSaveAsAccessMode.xlNoChange);
            workBook.Save();
            workBook.Close(true);
            excel.Quit();
        }
예제 #26
0
        internal void CreateExcelFile(string FileName)
        {
            //create
            object Nothing = System.Reflection.Missing.Value;
            var    app     = new Excel.Application();

            app.Visible = false;
            Excel.Workbook  workBook  = app.Workbooks.Add(Nothing);
            Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];

            worksheet.Name = FileName;
            //headline
            worksheet.Cells[1, 1] = "名称";
            worksheet.Cells[1, 2] = "编码";
            //worksheet.Cells[1, 2].numberFormatting = "@";
            worksheet.Cells[1, 3] = "简码";
            worksheet.Cells[1, 4] = "商品分类编码";
            worksheet.Cells[1, 5] = "税率";
            //worksheet.Cells[1, 5].numberFormatting = "formatnumber";
            worksheet.Cells[1, 6]  = "规格/厂牌";
            worksheet.Cells[1, 7]  = "计量单位";
            worksheet.Cells[1, 8]  = "适用税率";
            worksheet.Cells[1, 9]  = "含税标志";
            worksheet.Cells[1, 10] = "优惠政策类型";
            worksheet.Cells[1, 11] = "免税类型";

            worksheet.Columns[2].NumberFormatLocal = "@";//设置第二列为 文本格式
            worksheet.Columns[4].NumberFormatLocal = "@";

            worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
            workBook.Close(false, Type.Missing, Type.Missing);


            app.Quit();
        }
예제 #27
0
        private void ConvertAndSaveFile(Excel.Worksheet workSheet)
        {
            String directory = Path.GetDirectoryName(this.sourceFullPath);

            directory += "\\" + Path.GetFileNameWithoutExtension(this.sourceFullPath);
            directory += "\\";

            DirectoryInfo directoryInfo = new DirectoryInfo(directory);

            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }

            this.destFullPath = directory + workSheet.Name + this.destExtention;

            if (checkDeleteColumnValue == workSheet.Range[checkDeleteColumnCell].Value2.ToString())
            {
                workSheet.Columns[deleteColumn].Delete();
            }

            ((Excel.Range)workSheet.Rows[deleteRow, Type.Missing]).Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

            workSheet.SaveAs(this.destFullPath, Excel.XlFileFormat.xlCSV);
        }
예제 #28
0
        private void initializeWorkSheetGameModeEasy()
        {
            // Het verbinden van de path die nodig om de locatie te vinden van de Excel worksheet (highscores.xlsx).
            string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
            string path        = string.Format("{0}Resources\\highscores", System.IO.Path.GetFullPath(System.IO.Path.Combine(RunningPath, @"..\..\")));

            if (!File.Exists(path + "\\highscoresGMEasy.xls"))
            {
                xlApp = new Microsoft.Office.Interop.Excel.Application();
                object misValue = System.Reflection.Missing.Value;
                xlWorkBook  = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = xlWorkBook.Worksheets.get_Item(1);


                xlWorkSheet.Cells[1, 1] = "ID";
                xlWorkSheet.Cells[1, 2] = "Name";
                xlWorkSheet.Cells[1, 3] = "Score";

                xlWorkSheet.SaveAs(path + "\\highscoresGMEasy.xls");
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                Marshal.ReleaseComObject(xlWorkSheet);
                Marshal.ReleaseComObject(xlWorkBook);
                Marshal.ReleaseComObject(xlApp);
            }
        }
예제 #29
0
        public void ExportDataSetToExcel(DataSet ds, string fileName)
        {
            //Creae an Excel application instance
            Excel.Application excelApp = new Excel.Application();

            //Create an Excel workbook instance and open it from the predefined location
            Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();

            foreach (DataTable table in ds.Tables)
            {
                //Add a new worksheet to workbook with the Datatable name
                Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
                excelWorkSheet.Name = table.TableName;

                for (int i = 1; i < table.Columns.Count + 1; i++)
                {
                    excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
                }

                for (int j = 0; j < table.Rows.Count; j++)
                {
                    for (int k = 0; k < table.Columns.Count; k++)
                    {
                        excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
                    }
                }

                excelWorkSheet.SaveAs(table.TableName);
            }

            excelWorkBook.SaveAs(fileName);
            excelWorkBook.Close();
            excelApp.Quit();
        }
예제 #30
0
        public void WriteTable(DataTable dt, string filename)
        {
            if (!StartExcel())
            {
                return;
            }

            // Fill headers
            for (int colIndex = 0; colIndex < dt.Columns.Count; ++colIndex)
            {
                xlWorksheet.Cells[1, (colIndex + 1)] = dt.Columns[colIndex].ColumnName;
            }

            // Write data
            for (int rowIndex = 0; rowIndex < dt.Rows.Count; ++rowIndex)
            {
                for (int colIndex = 0; colIndex < dt.Columns.Count; ++colIndex)
                {
                    xlWorksheet.Cells[(rowIndex + 2), (colIndex + 1)] = dt.Rows[rowIndex][colIndex];
                }
            }

            xlWorksheet.SaveAs(filename);
            StopExcel();
        }
예제 #31
0
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            exportProgress.Minimum = 0;
            exportProgress.Maximum = TestInfoList.Count ;
            exportProgress.Value = 0;
            double value = 0;
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(exportProgress.SetValue);
            try
            {
                excelApp = new ApplicationClass();
                Workbooks myWorkBooks = excelApp.Workbooks;
                myWorkBooks.Open(templatePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                Sheets sheets = excelApp.Sheets;
                mySheet1 = (Worksheet)sheets[1];
                mySheet1.Activate();

                int rowCount = TestInfoList.Count + 2; ;//总行数

                //写入参数信息
                int paramCount = 0;//参数行数
                if (IsExportParams)
                {
                    paramCount = ParamList.Count * 4;
                    for (int i = 0; i < ParamList.Count; i++)
                    {
                        Model.Parameter p = ParamList[i];

                        Range r = mySheet1.get_Range(mySheet1.Cells[1, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[1, testInfoColumnCount + i * 4 + 4]);
                        r.Merge();
                        r.Value = p.ParamName;
                        r.Font.Bold = true;
                        r.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                        r.VerticalAlignment = XlHAlign.xlHAlignCenter;

                        Range r1 = mySheet1.get_Range(mySheet1.Cells[2, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[2, testInfoColumnCount + i * 4 + 4]);
                        r1.Value2 = paramContents;
                        r1.Font.Bold = true;

                        r1.EntireColumn.AutoFit();
                    }
                }

                //写入测试信息
                string[,] content = new string[rowCount, testInfoColumnCount + paramCount];
                //double?[,] paramContent = new double?[rowCount, paramCount];

                XDocument xdoc;
                BLL.TB_Dict dictBLL = new BLL.TB_Dict();
                for (int i = 0; i < TestInfoList.Count; i++)
                {
                    int rowIndex = i;
                    Model.TestInfoModel model = TestInfoList[i];

                    content[rowIndex, 0] = string.Format("测试{0}", i + 1);//测试顺序
                    content[rowIndex, 1] = model.Ath_Name;//姓名
                    content[rowIndex, 2] = model.TestDate.ToString("yyyy-MM-dd HH:mm");//测试日期
                    content[rowIndex, 3] = model.DJoint;//测试关节
                    content[rowIndex, 4] = model.DJointSide;//测试侧
                    content[rowIndex, 5] = model.DPlane;//运动方式
                    content[rowIndex, 6] = model.DTestMode;//测试模式
                    content[rowIndex, 7] = model.MotionRange;//运动范围
                    content[rowIndex, 8] = model.Speed;//测试速度
                    content[rowIndex, 9] = model.Break;//休息时间
                    content[rowIndex, 10] = model.NOOfSets;//测试组数
                    content[rowIndex, 11] = model.NOOfRepetitions;//重复次数
                    content[rowIndex, 12] = model.DInsuredSide;//受伤测
                    content[rowIndex, 13] = model.DGravitycomp;//重力补偿
                    if (IsExportParams)
                    {
                        string xmlPath = Model.AppPath.XmlDataDirPath + model.DataFileName;
                        xdoc = XDocument.Load(xmlPath);
                        List<XElement> action1 = xdoc.Descendants("action1").Elements<XElement>().ToList<XElement>();
                        List<XElement> action2 = xdoc.Descendants("action2").Elements<XElement>().ToList<XElement>();
                        for (int j = 0; j < ParamList.Count; j++)
                        {
                            int paramOneColumnIndex = j * 4;
                            double p1;
                            if (double.TryParse(action1[ParamList[j].Index].Attribute("max").Value, out p1)) {
                                //paramContent[rowIndex, paramOneColumnIndex] = p1;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 1] = p1;
                            }
                            double p2;
                            if (double.TryParse(action1[ParamList[j].Index].Attribute("avg").Value, out p2))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 1] = p2;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 2] = p2;
                            }
                            double p3;
                            if (double.TryParse(action2[ParamList[j].Index].Attribute("max").Value, out p3))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 2] = p3;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 3] = p3;
                            }
                            double p4;
                            if (double.TryParse(action2[ParamList[j].Index].Attribute("avg").Value, out p4))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 3] = p4;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 4] = p4;
                            }

                        }
                    }

                    //写进度条
                    value += 1;
                    Dispatcher.Invoke(updatePbDelegate,
                        System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, value });
                }
                //写入测试信息
                Range range1 = mySheet1.get_Range(mySheet1.Cells[3, 1], mySheet1.Cells[rowCount, testInfoColumnCount]);
                range1.Value2 = content;
                //写入参数信息
                //Range range2 = mySheet1.get_Range(mySheet1.Cells[3, testInfoColumnCount + 1], mySheet1.Cells[rowCount, testInfoColumnCount + paramCount]);
                //range2.Value2 = paramContent;

                //if (IsExportParams)
                //{
                //    rowCount = TestInfoList.Count + (ParamList.Count + 1) * TestInfoList.Count + 1;//信息行数+信息行数×参数行数+第一行列头信息
                //    paramCount = ParamList.Count + 1;//参数行数加1行参数名
                //}
                //else {
                //    rowCount = TestInfoList.Count + 1;
                //}

                //string[,] content = new string[rowCount, 13];

                //XDocument xdoc;
                //Model.TB_Dict actionModel;
                //BLL.TB_Dict dictBLL = new BLL.TB_Dict();
                //for (int i = 0; i < TestInfoList.Count; i++) {
                //    int rowIndex = i + i * paramCount;
                //    Model.TestInfoModel model = TestInfoList[i];

                //    content[rowIndex, 0] = model.Ath_Name;//姓名
                //    content[rowIndex, 1] = model.TestDate.ToString("yyyy-MM-dd HH:mm");//测试日期
                //    content[rowIndex, 2] = model.DJoint;//测试关节
                //    content[rowIndex, 3] = model.DJointSide;//测试侧
                //    content[rowIndex, 4] = model.DPlane;//运动方式
                //    content[rowIndex, 5] = model.DTestMode;//测试模式
                //    content[rowIndex, 6] = model.MotionRange;//运动范围
                //    content[rowIndex, 7] = model.Speed;//测试速度
                //    content[rowIndex, 8] = model.Break;//休息时间
                //    content[rowIndex, 9] = model.NOOfSets;//测试组数
                //    content[rowIndex, 10] = model.NOOfRepetitions;//重复次数
                //    content[rowIndex, 11] = model.DInsuredSide;//受伤测
                //    content[rowIndex, 12] = model.DGravitycomp;//重力补偿
                //    if (IsExportParams) {
                //        //写入参数信息
                //        actionModel = dictBLL.GetModel(model.Joint, model.Plane, model.Test_Mode);
                //        content[rowIndex + 1, 0] = "所选测试顺序";
                //        content[rowIndex + 1, 1] = "参数";
                //        content[rowIndex + 1, 2] = actionModel.actionone + "(极值)";
                //        content[rowIndex + 1, 3] = actionModel.actionone + "(平均值)";
                //        content[rowIndex + 1, 4] = actionModel.actiontwo + "(极值)";
                //        content[rowIndex + 1, 5] = actionModel.actiontwo + "(平均值)";
                //        string xmlPath = Model.AppPath.XmlDataDirPath + model.DataFileName;
                //        xdoc = XDocument.Load(xmlPath);
                //        List<XElement> action1 = xdoc.Descendants("action1").Elements<XElement>().ToList<XElement>();
                //        List<XElement> action2 = xdoc.Descendants("action2").Elements<XElement>().ToList<XElement>();
                //        for (int j = 0; j < ParamList.Count; j++)
                //        {
                //            content[rowIndex + 1 + j + 1, 0] = "测试" + (i + 1);
                //            content[rowIndex + 1 + j + 1, 1] = ParamList[j].ParamName;
                //            content[rowIndex + 1 + j + 1, 2] = action1[ParamList[j].Index].Attribute("max").Value;
                //            content[rowIndex + 1 + j + 1, 3] = action1[ParamList[j].Index].Attribute("avg").Value;
                //            content[rowIndex + 1 + j + 1, 4] = action2[ParamList[j].Index].Attribute("max").Value;
                //            content[rowIndex + 1 + j + 1, 5] = action2[ParamList[j].Index].Attribute("avg").Value;
                //        }
                //    }

                //    //写进度条
                //    value += 1;
                //    Dispatcher.Invoke(updatePbDelegate,
                //        System.Windows.Threading.DispatcherPriority.Background,
                //        new object[] { ProgressBar.ValueProperty, value });
                //}
                //Range range = mySheet1.get_Range(mySheet1.Cells[2, 1], mySheet1.Cells[rowCount, 13]);
                //range.Value2 = content;
                mySheet1.SaveAs(choosePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                myWorkBooks.Close();
                excelApp.Quit();
                MessageBox.Show("导出成功!", "系统信息");
                System.Windows.Window.GetWindow(this).Close();
            }
            catch (Exception ee) {
                MessageBox.Show("导出出错!\r\n错误信息为:" + ee.Message, "系统错误");
            }
        }
예제 #32
0
        public void Export(List<List<XElement>> datalist,string savePath)
        {
            try
            {
                excelApp = new ApplicationClass();
                Workbooks myWorkBooks = excelApp.Workbooks;
                myWorkBooks.Open(templatePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                Sheets sheets = excelApp.Sheets;
                mySheet1 = (Worksheet)sheets[1];
                mySheet1.Activate();

                int rowCount = 1 + 2; ;//总行数

                //写入参数信息
                int paramCount = 0;//参数行数
                List<DSJL.Model.Parameter> paramList = DSJL.Model.Parameter.GetAllParams();
                paramCount = paramList.Count * 4;
                for (int i = 0; i < paramList.Count; i++)
                {
                    Model.Parameter p = paramList[i];

                    Range r = mySheet1.get_Range(mySheet1.Cells[1, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[1, testInfoColumnCount + i * 4 + 4]);
                    r.Merge();
                    r.Value = p.ParamName;
                    r.Font.Bold = true;
                    r.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                    r.VerticalAlignment = XlHAlign.xlHAlignCenter;

                    Range r1 = mySheet1.get_Range(mySheet1.Cells[2, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[2, testInfoColumnCount + i * 4 + 4]);
                    r1.Value2 = paramContents;
                    r1.Font.Bold = true;

                    r1.EntireColumn.AutoFit();
                }

                //写入测试信息
                string[,] content = new string[rowCount, testInfoColumnCount + paramCount];
                //double?[,] paramContent = new double?[rowCount, paramCount];

                BLL.TB_Dict dictBLL = new BLL.TB_Dict();

                int rowIndex = 0;

                //content[rowIndex, 0] ="";//测试顺序
                //content[rowIndex, 1] = model.Ath_Name;//姓名
                //content[rowIndex, 2] = model.TestDate.ToString("yyyy-MM-dd HH:mm");//测试日期
                //content[rowIndex, 3] = model.DJoint;//测试关节
                //content[rowIndex, 4] = model.DJointSide;//测试侧
                //content[rowIndex, 5] = model.DPlane;//运动方式
                //content[rowIndex, 6] = model.DTestMode;//测试模式
                //content[rowIndex, 7] = model.MotionRange;//运动范围
                //content[rowIndex, 8] = model.Speed;//测试速度
                //content[rowIndex, 9] = model.Break;//休息时间
                //content[rowIndex, 10] = model.NOOfSets;//测试组数
                //content[rowIndex, 11] = model.NOOfRepetitions;//重复次数
                //content[rowIndex, 12] = model.DInsuredSide;//受伤测
                //content[rowIndex, 13] = model.DGravitycomp;//重力补偿

                List<XElement> action1 = datalist[0];
                List<XElement> action2 = datalist[1];
                for (int j = 0; j < paramList.Count; j++)
                {
                    int paramOneColumnIndex = j * 4;
                    double p1;
                    if (double.TryParse(action1[paramList[j].Index].Attribute("max").Value, out p1))
                    {
                        //paramContent[rowIndex, paramOneColumnIndex] = p1;
                        mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 1] = p1;
                    }
                    double p2;
                    if (double.TryParse(action1[paramList[j].Index].Attribute("avg").Value, out p2))
                    {
                        //paramContent[rowIndex, paramOneColumnIndex + 1] = p2;
                        mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 2] = p2;
                    }
                    double p3;
                    if (double.TryParse(action2[paramList[j].Index].Attribute("max").Value, out p3))
                    {
                        //paramContent[rowIndex, paramOneColumnIndex + 2] = p3;
                        mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 3] = p3;
                    }
                    double p4;
                    if (double.TryParse(action2[paramList[j].Index].Attribute("avg").Value, out p4))
                    {
                        //paramContent[rowIndex, paramOneColumnIndex + 3] = p4;
                        mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 4] = p4;
                    }

                }

                //写入测试信息
                Range range1 = mySheet1.get_Range(mySheet1.Cells[3, 1], mySheet1.Cells[rowCount, testInfoColumnCount]);
                range1.Value2 = content;

                mySheet1.SaveAs(savePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                myWorkBooks.Close();
                excelApp.Quit();

            }
            catch (Exception ee)
            {
                throw ee;
            }
            finally {
                DSJL.Model.Parameter.CheckDefault();
            }
        }