Пример #1
0
        private void btnexport_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    wb    = excel.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet   ws    = null;
            ws      = wb.Sheets["Sheet1"];
            ws      = wb.ActiveSheet;
            ws.Name = "Allotments";
            for (int i = 1; i < gdvallotment.Columns.Count + 1; i++)
            {
                ws.Cells[1, i] = gdvallotment.Columns[i - 1].HeaderText;
            }
            for (int i = 0; i < gdvallotment.Columns.Count; i++)
            {
                for (int j = 0; j < gdvallotment.Columns.Count; j++)
                {
                    ws.Cells[i + 2, j + 1] = gdvallotment.Rows[i].Cells[j].Value.ToString();
                }
            }
            var saveFileDialogue = new SaveFileDialog();

            saveFileDialogue.FileName   = "Allotments";
            saveFileDialogue.DefaultExt = ".xlsx";
            if (saveFileDialogue.ShowDialog() == DialogResult.OK)
            {
                ws.SaveAs(saveFileDialogue.FileName, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            excel.Quit();
            MessageBox.Show("File Saved Successfully");
        }
Пример #2
0
        private void exportBT_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();

            saveFile.Title            = "保存文件";
            saveFile.Filter           = "Excel 文件(*.xlsx)|*.xlsx|All files(*.*)|*.*";
            saveFile.RestoreDirectory = true;
            saveFile.FilterIndex      = 1;
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                string Savepath = saveFile.FileName;
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                object Nothing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.Workbook  workBook  = app.Workbooks.Add(Nothing);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = workBook.Sheets[1];
                worksheet.Name = "sheet1";
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            worksheet.Cells[row.Index + 1, cell.ColumnIndex + 1] = "'" + cell.Value.ToString();
                        }
                    }
                }
                worksheet.SaveAs(Savepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
                workBook.Close(false, Type.Missing, Type.Missing);
                app.Quit();
            }
        }
Пример #3
0
        //生成绩效目标表
        private void Generate_KPI_Target(KpiInfoViewModel kpi, Microsoft.Office.Interop.Excel.Worksheet wsh)
        {
            try
            {
                wsh.Cells[2, 2].value  = kpi.KPIInfo.Year + "年" + kpi.KPIInfo.Period.Substring(0, 2) + "绩效指标考核表——国内专利事业部+" + kpi.KPIInfo.Zone + "+" + kpi.KPIInfo.Name;
                wsh.Cells[3, 2].value  = "考核周期:" + kpi.KPIInfo.Period;
                wsh.Cells[6, 7].value  = kpi.KPIInfo.DonePoint_Target;
                wsh.Cells[7, 7].value  = kpi.KPIInfo.FirstVirsionPoint_Target;
                wsh.Cells[8, 7].value  = kpi.KPIInfo.PatentDegree_Target;
                wsh.Cells[9, 7].value  = kpi.KPIInfo.InTimePortion_Target;
                wsh.Cells[6, 8].value  = 0.3;
                wsh.Cells[7, 8].value  = 0.25;
                wsh.Cells[8, 8].value  = 0.1;
                wsh.Cells[9, 8].value  = 0.2;
                wsh.Cells[15, 4].value = kpi.KPIInfo.Name;
                wsh.Cells[16, 4].value = kpi.KPIInfo.Examiner;
                wsh.Cells[15, 7].value = kpi.KPIInfo.Position;
                wsh.Cells[16, 7].value = kpi.KPIInfo.Examiner_Positon;

                //华进员工绩效考核表——国内专利事业部+广州电子部+蔡抒枫
                string file = "C:\\WORK\\绩效考核\\华进员工绩效考核表——国内专利事业部+" + kpi.KPIInfo.Zone + "+" + kpi.KPIInfo.Name + ".xlsx";
                if (File.Exists(file))
                {
                    File.Delete(file);
                }

                wsh.SaveAs(file);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
        }
Пример #4
0
        private void button7_Click(object sender, EventArgs e)
        {
            int i, j;

            Microsoft.Office.Interop.Excel.Application exApp = new Microsoft.Office.Interop.Excel.Application();
            System.Diagnostics.Process ExelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL").Last();
            exApp.Workbooks.Open(Environment.CurrentDirectory + "\\2.xlsx");
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)exApp.ActiveSheet;
            for (i = 0; i < dataGridView3.ColumnCount; i++)
            {
                for (j = 0; j < dataGridView3.RowCount; j++)
                {
                    workSheet.Cells[j + 2, i + 2] = dataGridView3[i, j].Value.ToString();
                    workSheet.Cells[j + 2, i + 2].Interior.Color = dataGridView3[i, j].Style.BackColor;
                }
            }
            try
            {
                workSheet.SaveAs(Environment.CurrentDirectory + "Расхождения при сверке " + comboBox1.Text + "-" + comboBox2.Text + DateTime.Now.ToString("ddMMyyyy") + ".xlsx", Type.Missing);
                Logs.Write("Выгрузка в эксель расхождений" + "Расхождения при сверке " + comboBox1.Text + "-" + comboBox2.Text + DateTime.Now.ToString("ddMMyyyy") + ".xlsx");
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
            exApp.Visible = true;
        }
Пример #5
0
        private void Btn_DataSave_Click(object sender, EventArgs e)
        {                                           //数据存储
            /*******************数据导入Excel**********************/
            string fileName = ShowSaveFileDialog(); //文件的保存路径和文件名

            try
            {
                // 创建Excel文档
                Microsoft.Office.Interop.Excel.Application ExcelApp
                    = new Microsoft.Office.Interop.Excel.Application();
                //创建EXCEL文档
                Microsoft.Office.Interop.Excel.Workbook ExcelDoc = ExcelApp.Workbooks.Add(Type.Missing);
                // 创建一个EXCEL页

                Microsoft.Office.Interop.Excel.Worksheet xlSheet = ExcelDoc.Worksheets.Add(Type.Missing,
                                                                                           Type.Missing, Type.Missing, Type.Missing);
                ExcelApp.DisplayAlerts = false;

                // 单元格下标是从[1,1]开始的
                xlSheet.Cells[1, 1] = "序号";
                xlSheet.Cells[1, 2] = "电压";
                xlSheet.Cells[1, 3] = "SOC";
                xlSheet.Cells[1, 4] = "SOH";
                xlSheet.Cells[1, 5] = "温度";
                //遍历存数据
                for (int i = 0; i < 100; i++)
                {
                    xlSheet.Cells[i + 2, 1] = "电池" + i.ToString();
                }
                for (int i = 0; i < 100; i++)
                {
                    xlSheet.Cells[i + 2, 2] = Voltage_Battery[i].Text;
                }
                for (int i = 0; i < 100; i++)
                {
                    xlSheet.Cells[i + 2, 3] = Soc_Battery[i].Text;
                }
                for (int i = 0; i < 100; i++)
                {
                    xlSheet.Cells[i + 2, 4] = Soh_Battery[i].Text;
                }
                for (int i = 0; i < 100; i++)
                {
                    xlSheet.Cells[i + 2, 5] = Temperature_Battery[i].Text;
                }

                // 文件保存完毕输出信息//将此页保存到我们新建的文档中
                xlSheet.SaveAs(fileName);
                //释放EXCEL资源
                ExcelDoc.Close(Type.Missing, fileName, Type.Missing);
                ExcelApp.Quit();
                MessageBox.Show("数据保存成功!");
            }
            catch
            {
                MessageBox.Show("数据保存失败!");
            }
        }
        private void ExportSSummarizeList(object[] parameter)
        {
            string exepath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string file    = exepath + "MyData\\导出表.xlsx";

            Microsoft.Office.Interop.Excel.Application app    = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks   wbks   = app.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook    wbk    = wbks.Add(file);
            Microsoft.Office.Interop.Excel.Sheets      sheets = wbk.Sheets;
            Microsoft.Office.Interop.Excel.Worksheet   wsh    = sheets["Sheet1"];
            int i = 0;

            if (KPISSummarizelist.Count > 0)
            {
                foreach (KPIIndicators item in KPISSummarizelist)
                {
                    wsh.Cells[i + 2, 1].value = item.Name;
                    wsh.Cells[i + 2, 2].value = item.Period;
                    for (int j = 0; j < 10; j++)
                    {
                        wsh.Cells[i + 2, j * 2 + 3].value = item.IndicatorNames[j];
                        wsh.Cells[i + 2, j * 2 + 4].value = item.Indicators[j];
                    }
                    wsh.Cells[i + 2, 23].value = item.Score;
                    wsh.Cells[i + 2, 24].value = item.Grade;
                    i++;
                }
                if (!Directory.Exists(FilePathS + "\\汇总"))
                {
                    Directory.CreateDirectory(FilePathS + "\\汇总");
                }
                string fileSummarize = FilePathS + "\\汇总\\干部汇总表.xlsx";
                if (File.Exists(fileSummarize))
                {
                    try
                    {
                        File.Delete(fileSummarize);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        throw;
                    }
                }

                wsh.SaveAs(fileSummarize);
                wbks.Close();
                MessageBox.Show("生成完毕!", "", MessageBoxButton.OK, MessageBoxImage.Information);
                Process.Start("explorer.exe ", FilePathS + "\\汇总");
            }
            else
            {
                MessageBox.Show("没有数据", "出错了", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #7
0
        public bool saveTo(string filename, bool alert)
        {
            bool r = false;

            oexcel.DisplayAlerts = alert;
            osheet.SaveAs(filename);
            //osheet.SaveAs(filename,Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795,Type.Missing,Type.Missing,Type.Missing,
            //                Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
            oexcel.DisplayAlerts = true;
            r = true;
            return(r);
        }
Пример #8
0
        private void ExportDoneTable(object[] parameter)
        {
            string exepath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string file    = exepath + "MyData\\绩效汇总表-模板.xls";

            Microsoft.Office.Interop.Excel.Application app    = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks   wbks   = app.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook    wbk    = wbks.Add(file);
            Microsoft.Office.Interop.Excel.Sheets      sheets = wbk.Sheets;
            Microsoft.Office.Interop.Excel.Worksheet   wsh    = sheets["sheet1"];

            int i = 0;

            foreach (KpiInfoViewModel kpi in SelectedKpiInfos)
            {
                wsh.Cells[i + 2, 1].value  = kpi.KPIInfo.Period;
                wsh.Cells[i + 2, 2].value  = kpi.KPIInfo.Zone;
                wsh.Cells[i + 2, 3].value  = kpi.KPIInfo.Name;
                wsh.Cells[i + 2, 4].value  = kpi.KPIInfo.DonePoint_Target;
                wsh.Cells[i + 2, 5].value  = kpi.KPIInfo.FirstVirsionPoint_Target;
                wsh.Cells[i + 2, 6].value  = kpi.KPIInfo.PatentDegree_Target;
                wsh.Cells[i + 2, 7].value  = kpi.KPIInfo.InTimePortion_Target;
                wsh.Cells[i + 2, 8].value  = kpi.KPIInfo.Score_Cowork;
                wsh.Cells[i + 2, 9].value  = kpi.KPIInfo.Score_Passion;
                wsh.Cells[i + 2, 10].value = kpi.KPIInfo.Score_Selfdrive;
                wsh.Cells[i + 2, 11].value = kpi.KPIInfo.DonePoint;
                wsh.Cells[i + 2, 12].value = kpi.KPIInfo.PatentDegree;
                wsh.Cells[i + 2, 13].value = kpi.KPIInfo.InTimePortion;
                wsh.Cells[i + 2, 14].value = kpi.KPIInfo.FirstVirsionPoint;

                wsh.Cells[i + 2, 15].value = kpi.KPIInfo.Position;
                wsh.Cells[i + 2, 16].value = kpi.KPIInfo.Examiner;
                wsh.Cells[i + 2, 17].value = kpi.KPIInfo.Examiner_Positon;
                wsh.Cells[i + 2, 18].value = kpi.KPIInfo.Score;
                wsh.Cells[i + 2, 20].value = kpi.KPIInfo.Comment;
                i++;
            }

            string fileSummarize = "C:\\WORK\\绩效考核\\绩效考核汇总表.xlsx";

            if (File.Exists(fileSummarize))
            {
                File.Delete(fileSummarize);
            }

            wsh.SaveAs(fileSummarize);
            wbks.Close();
            MessageBox.Show("生成完毕!", "", MessageBoxButton.OKCancel, MessageBoxImage.Information);
        }
Пример #9
0
        private void btn_ExportRecord_Click(object sender, EventArgs e)
        {
            string         saveFileName = "";
            SaveFileDialog saveDialog   = new SaveFileDialog();

            saveDialog.DefaultExt = "xls";
            saveDialog.Filter     = "Excel文件|*.xls";
            saveDialog.FileName   = "Record";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0)
            {
                return;                                //被点了取消
            }
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            object missing = System.Reflection.Missing.Value;

            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook  workbook  = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1


            System.Data.DataTable dt = new System.Data.DataTable();
            ExportAllRecord(ref dt);

            //写入列名
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
            }
            //写入数值
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
                }
            }
            worksheet.SaveAs(saveFileName, 56, missing, missing, missing, missing, missing, missing, missing);
            workbook.Close(missing, missing, missing);
            xlApp.Quit();

            DevComponents.DotNetBar.MessageBoxEx.Show("文件已导出!");
        }
Пример #10
0
        /// <summary>
        /// 导出Excel文件
        /// </summary>
        /// /// <param name="dataSet"></param>
        /// <param name="dataTable">数据集</param>
        /// <param name="isShowExcle">导出后是否打开文件</param>
        /// <returns></returns>
        public static bool DataTableToExcel(string filePath, System.Data.DataTable dataTable, bool isShowExcle)
        {
            //System.Data.DataTable dataTable = dataSet.Tables[0];
            int rowNumber    = dataTable.Rows.Count;
            int columnNumber = dataTable.Columns.Count;
            int colIndex     = 0;

            if (rowNumber == 0)
            {
                return(false);
            }

            Microsoft.Office.Interop.Excel.Application excel     = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    workbook  = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet   worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            excel.Visible = isShowExcle;
            Microsoft.Office.Interop.Excel.Range range;


            foreach (DataColumn col in dataTable.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }

            object[,] objData = new object[rowNumber, columnNumber];

            for (int r = 0; r < rowNumber; r++)
            {
                for (int c = 0; c < columnNumber; c++)
                {
                    objData[r, c] = dataTable.Rows[r][c];
                }
            }

            range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]);

            range.Value2 = objData;

            range.NumberFormatLocal = "@";

            worksheet.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            //excel.Quit();
            return(true);
        }
Пример #11
0
        public void creatExcel(string xlsfile)
        {
            if (File.Exists(xlsfile))
            {
                File.Delete(xlsfile);
            }
            //1.创建Applicaton对象
            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();

            //2.得到workbook对象,打开已有的文件
            Microsoft.Office.Interop.Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(Missing.Value);

            //3.指定要操作的Sheet
            Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelBook.Sheets[1];

            //在第一列的左边插入一列  1:第一列
            //xlShiftToRight:向右移动单元格   xlShiftDown:向下移动单元格
            //Range Columns = (Range)xSheet.Columns[1, System.Type.Missing];
            //Columns.Insert(XlInsertShiftDirection.xlShiftToRight, Type.Missing);

            ExcelApp.Visible = true;
            //4.向相应对位置写入相应的数据
            ExcelSheet.Cells[1][1] = "this is a test.";

            //5.保存保存WorkBook
            //xBook.Save();
            ExcelApp.DisplayAlerts = false;
            ExcelBook.SaveAs(xlsfile);
            //6.从内存中关闭Excel对象

            ExcelSheet.SaveAs(xlsfile);
            ExcelSheet = null;

            ExcelBook.Close();
            ExcelBook = null;
            //关闭EXCEL的提示框
            ExcelApp.DisplayAlerts = false;
            //Excel从内存中退出

            ExcelApp.Quit();
            ExcelApp = null;
        }
Пример #12
0
        private void createLog()
        {
            string fileName = Application.StartupPath + "\\日志文件\\日志文件.xlsx";

            if (!File.Exists(fileName))
            {
                allCount = 0;
                object Nothing = Missing.Value;
                var    app     = new Microsoft.Office.Interop.Excel.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook  workBook  = app.Workbooks.Add(Nothing);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1];
                worksheet.Name         = "日志文件";
                worksheet.Cells[1, 1]  = "发送邮箱";
                worksheet.Cells[1, 2]  = "工资明细文件";
                worksheet.Cells[1, 3]  = "发送时间点";
                worksheet.Cells[1, 4]  = "完成时间点";
                worksheet.Cells[1, 5]  = "总共发送时间";
                worksheet.Cells[1, 6]  = "总共次数";
                worksheet.Cells[1, 7]  = "成功次数";//标题
                worksheet.Cells[1, 8]  = "失败次数";
                worksheet.Cells[1, 9]  = "成功率";
                worksheet.Cells[1, 10] = "错误代码                                       ";//10个tab
                try
                {
                    worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
                    workBook.Close(false, Type.Missing, Type.Missing);
                    app.Quit();
                    app = null;
                }
                catch
                {
                    MessageBox.Show("日志文件创建不成功");
                }
            }
            else
            {
                allCount = excelToDS(fileName, 1).Tables[0].Rows.Count;
            }
        }
Пример #13
0
        public bool saveTo(string filename, bool alert)
        {
            bool r = false;

            try
            {
                oexcel.DisplayAlerts = alert;
                osheet.SaveAs(filename);

                /*
                 *  Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, Type.Missing, Type.Missing, Type.Missing,
                 *              Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                 */
                oexcel.DisplayAlerts = true;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            r = true;
            return(r);
        }
Пример #14
0
        private void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            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;
            workSheet.Cells[1, 1] = "Фамилия";
            workSheet.Cells[1, 2] = "Имя";
            workSheet.Cells[1, 3] = "Отчество";
            workSheet.Cells[1, 4] = "Гражданство";
            workSheet.Cells[1, 5] = "Телефон";
            workSheet.Cells[1, 6] = "Паспорт";
            int rowExcel = 2;
            var table    = DataGrid.ItemsSource as List <Persons>;

            for (int i = 0; i < DataGrid.Items.Count; i++)
            {
                workSheet.Cells[rowExcel, "A"] = table[i].Surname;
                workSheet.Cells[rowExcel, "B"] = table[i].Name;
                workSheet.Cells[rowExcel, "C"] = table[i].Patronymic;
                workSheet.Cells[rowExcel, "D"] = table[i].Country;
                workSheet.Cells[rowExcel, "E"] = table[i].Phone;
                workSheet.Cells[rowExcel, "F"] = table[i].PassportNumber;
                ++rowExcel;
            }
            Microsoft.Office.Interop.Excel.Range range = workSheet.Range[workSheet.Cells[1, 1], workSheet.Cells[100, 100]];
            range.EntireColumn.AutoFit();
            range.EntireRow.AutoFit();
            SWF.SaveFileDialog saveDialog = new SWF.SaveFileDialog
            {
                AddExtension = true,
                Filter       = "Excel files (*.xlsx)|*.xlsx"
            };
            if (saveDialog.ShowDialog() == SWF.DialogResult.OK)
            {
                workSheet.SaveAs(saveDialog.FileName);
            }
            exApp.Visible = true;
            exApp.Workbooks.Open(saveDialog.FileName);
        }
Пример #15
0
        public static void Creat()
        {
            // 文件保存路径及名称
            string fileName = @"F:\trainCrew\test" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".xlsx";

            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    ExcelDoc = ExcelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet   xlSheet  = ExcelDoc.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ExcelApp.DisplayAlerts = false;

            // 单元格下标是从[1,1]开始的
            xlSheet.Cells[1, 1] = "fitness";

            for (int i = 2; i < Common.fitData.Count(); i++)
            {
                xlSheet.Cells[i, 1] = Common.fitData[i - 2];
            }

            // 文件保存
            xlSheet.SaveAs(fileName);
            ExcelDoc.Close(Type.Missing, fileName, Type.Missing);
            ExcelApp.Quit();
        }
Пример #16
0
        public Boolean convert()
        {
            Boolean     rst   = false;
            Application excel = new Application();

            try
            {
                excel.Workbooks.Open(Filename: pathFileToOpen);
                excel.Visible = false;
                if (excel.Workbooks.Count > 0)
                {
                    IEnumerator wsEnumerator = excel.ActiveWorkbook.Worksheets.GetEnumerator();

                    object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
                    int    i      = 1;
                    while (wsEnumerator.MoveNext())
                    {
                        Microsoft.Office.Interop.Excel.Worksheet wsCurrent = (Microsoft.Office.Interop.Excel.Worksheet)wsEnumerator.Current;
                        String outputFile = "excelFile" + "." + i.ToString() + ".html";
                        wsCurrent.SaveAs(Filename: pathFileToSave, FileFormat: format);
                        ++i;
                        break;
                    }
                    excel.Workbooks.Close();
                }
            }
            catch (Exception ex)
            {
                rst = false;
            }
            finally
            {
                excel.Application.Quit();
                rst = true;
            }
            return(rst);
        }
Пример #17
0
        private void ExportToXLSX()
        {
            Microsoft.Office.Interop.Excel.Application application =
                new Microsoft.Office.Interop.Excel.Application();
            application.Workbooks.Add();
            Microsoft.Office.Interop.Excel.Worksheet worksheet =
                application.ActiveSheet;

            worksheet.Cells[1, 1] = "ID";
            worksheet.Cells[1, 2] = "Header";
            worksheet.Cells[1, 3] = "Text";
            worksheet.Cells[1, 4] = "CreationData";
            worksheet.Cells[1, 5] = "Author";

            var cellRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 5]];

            var allNews = AppData.Context.NewsItem.ToList().
                          OrderBy(p => p.CreationDate).ToList();

            for (int i = 0; i < allNews.Count(); i++)
            {
                var currentNews = allNews[i];

                worksheet.Cells[i + 2, 1] = currentNews.Id;
                worksheet.Cells[i + 2, 2] = currentNews.Header;
                worksheet.Cells[i + 2, 3] = currentNews.Text;
                worksheet.Cells[i + 2, 4] = currentNews.CreationDate.ToString("dd:MM:yyyy HH:mm");
                worksheet.Cells[i + 2, 5] = currentNews.Author.NickName;
            }
            checkExportDirectory();

            worksheet.SaveAs($"{AppDomain.CurrentDomain.BaseDirectory}Export" +
                             $"\\Export_News_XLSX_{DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss")}.xlsx");
            application.Quit();
            MessageBox.Show("Данные выгружены");
        }
Пример #18
0
        //Экспорт в Excel

        public void ExportToExcel(DataGridView dgv)
        {
            saveFile = new SaveFileDialog();

            saveFile.Filter = @"Excel файлы (*.xlsx)|*.xlsx";

            saveFile.FileName = "Экспорт библиотека " + DateTime.Now.Day + "." + DateTime.Now.Month + "." +
                                DateTime.Now.Year + ".xlsx";

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                string pathToFile = saveFile.FileName;

                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;

                exApp.Columns.ColumnWidth       = 30;
                exApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;


                for (int i = 0; i < dgv.RowCount; i++)
                {
                    for (int j = 1; j < dgv.ColumnCount; j++)
                    {
                        exApp.Cells[i + 1, j] = dgv.Rows[i].Cells[j].Value;
                    }
                }

                worksheet.SaveAs(pathToFile);
                exApp.Quit();
                MessageBox.Show(@"Экспорт успешно выполнен!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Пример #19
0
        static string ExportToExcelSheet() //now the all information in the datatble now it is converted to excel
        {
            DataTable Table         = OriginaldataTable.Copy();
            string    ExcelFilePath = Constant.FileOnLocalSystem;

            try
            {
                Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); //creating the excel sheet
                excelApp.Workbooks.Add();
                Microsoft.Office.Interop.Excel.Worksheet workSheet = excelApp.ActiveSheet;
                for (int count = 0; count < Table.Columns.Count; count++)//retriving the column name from datatable and stored on excel
                {
                    workSheet.Cells[1, (count + 1)] = Table.Columns[count].ColumnName;
                }
                for (int Count = 0; Count < Table.Rows.Count; Count++) //retriveing the each cell from datatable then it will be added to the excel sheet
                {
                    for (int InnerLoop = 0; InnerLoop < Table.Columns.Count; InnerLoop++)
                    {
                        workSheet.Cells[(Count + 2), (InnerLoop + 1)] = Table.Rows[Count][InnerLoop];
                    }
                }
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(ExcelFilePath + ".xlsx");
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();                                  //delete the existing one
                }
                workSheet.SaveAs(ExcelFilePath);                        //saved on given path
                excelApp.Quit();
            }
            catch (Exception ex)
            {
                LogClass.RecordException(ex);
                throw new Exception();
            }
            return(ExcelFilePath);
        }
Пример #20
0
        /// <summary>
        /// 复制Map的中文文本
        /// </summary>
        private void CopyCnMapTxt()
        {
            Microsoft.Office.Interop.Excel.Workbook  xBook   = null;
            Microsoft.Office.Interop.Excel.Worksheet xSheet  = null;
            Microsoft.Office.Interop.Excel.Workbook  xBook2  = null;
            Microsoft.Office.Interop.Excel.Worksheet xSheet2 = null;
            List <string> enSb = new List <string>();
            List <string> cnSb = new List <string>();
            Dictionary <string, List <string> > txtMap = new Dictionary <string, List <string> >();

            try
            {
                // 创建Application对象
                this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

                // 得到WorkBook对象, 打开已有的文件
                xBook = this.xApp.Workbooks._Open(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\mapText_jp.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                xBook2 = this.xApp.Workbooks._Open(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\mapText_en.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 显示进度条
                this.ResetProcessBar(xBook.Sheets.Count);

                int sheetIndex = -1;
                int line       = 1;
                for (int i = 1; i <= xBook.Sheets.Count; i++)
                {
                    // 更新进度条
                    this.ProcessBarStep();

                    xSheet     = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[i];
                    sheetIndex = -1;
                    for (int j = i; j <= xBook2.Sheets.Count; j++)
                    {
                        xSheet2 = (Microsoft.Office.Interop.Excel.Worksheet)xBook2.Sheets[j];
                        if (xSheet.Name.Equals(xSheet2.Name))
                        {
                            sheetIndex = j;
                            break;
                        }
                    }

                    if (sheetIndex == -1)
                    {
                        continue;
                    }

                    line = 1;
                    while (true)
                    {
                        Microsoft.Office.Interop.Excel.Range rngJp = xSheet.get_Range("G" + line, Missing.Value);
                        Microsoft.Office.Interop.Excel.Range rngEn = xSheet2.get_Range("G" + line, Missing.Value);
                        if (rngEn != null && !string.IsNullOrEmpty(rngEn.Value2 as string))
                        {
                            rngJp.Value2 = rngEn.Value2;
                            line++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                xSheet  = null;
                xBook   = null;
                xSheet2 = null;
                xBook2  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }

                // 隐藏进度条
                this.CloseProcessBar();

                // 保存
                xSheet.SaveAs(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\mapText_jp2.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            }
            catch (Exception me)
            {
                MessageBox.Show(me.Message);
            }
            finally
            {
                // 隐藏进度条
                this.CloseProcessBar();

                // 清空各种对象
                xSheet  = null;
                xBook   = null;
                xSheet2 = null;
                xBook2  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }
            }
        }
Пример #21
0
        public void printAll(DataTable dt)
        {
            if (dt != null)
            {
                try
                {
                    //保存文件
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter           = "导出Excel (*.xls)|*.xls";
                    saveFileDialog.FilterIndex      = 0;
                    saveFileDialog.RestoreDirectory = true;
                    saveFileDialog.CreatePrompt     = false;
                    saveFileDialog.Title            = "导出文件保存路径";
                    saveFileDialog.ShowDialog();
                    string strName = saveFileDialog.FileName;
                    if (strName.Length != 0)
                    {
                        System.Reflection.Missing miss = System.Reflection.Missing.Value;
                        //实例化一个excel对象
                        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                        excel.Application.Workbooks.Add(true);
                        excel.Visible = false;
                        if (excel == null)
                        {
                            MessageBox.Show("Excel无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
                        Microsoft.Office.Interop.Excel.Workbook  book  = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
                        Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
                        sheet.Name = "sheet1";
                        //int m = 0, n = 0;

                        //生成表头
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                        }
                        //写入数据
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                for (int j = 0; j < dt.Columns.Count; j++)
                                {
                                    string str = dt.Rows[i][j].ToString();
                                    excel.Cells[i + 2, j + 1] = str;
                                }
                            }
                        }
                        sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                        book.Close(false, miss, miss);
                        books.Close();
                        excel.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

                        GC.Collect();
                        MessageBox.Show("数据已成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        System.Diagnostics.Process.Start(strName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示");
                }
            }
        }
Пример #22
0
        /// <summary>
        /// 导出Excel文件
        /// </summary>
        public static int DataTableToExcel(DataTable dt, string title, string columns, string sheetName, string fileName)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter      = "导出Excel (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.Title       = "导出文件保存路径";
            saveFileDialog.FileName    = "LZ_" + fileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string strName = saveFileDialog.FileName;
                if (strName.Length != 0)
                {
                    System.Reflection.Missing miss = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    excel.Application.Workbooks.Add(true);;
                    excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
                    if (excel == null)
                    {
                        Logger.Error("Excel文件保存失败。", null);
                        return(CConstant.EXPORT_FAILURE);
                    }
                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook  book  = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
                    sheet.Name = sheetName;
                    int m = 0, n = 0;
                    //生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去
                    string[] strHeader = title.Split(',');
                    string[] strColumns = columns.Split(',');
                    for (int i = 0; i < strHeader.Length; i++)
                    {
                        excel.Cells[1, i + 1] = strHeader[i].ToString();
                    }
                    //填充数据
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];
                        //j也是从1开始 原因如上 每个人需求不一样
                        int j = 1;
                        foreach (string str in strColumns)
                        {
                            try
                            {
                                if (dr[str.Trim()].GetType() == typeof(string))
                                {
                                    excel.Cells[i + 2, j] = "'" + dr[str.Trim()].ToString();
                                    j++;
                                }
                                else
                                {
                                    excel.Cells[i + 2, j] = dr[str.Trim()].ToString();
                                    j++;
                                }
                            }
                            catch
                            {
                                j++;
                                continue;
                            }
                        }
                    }
                    try
                    {
                        sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                        book.Close(false, miss, miss);
                        books.Close();
                        excel.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                        GC.Collect();
                        //MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //System.Diagnostics.Process.Start(strName);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Excel文件保存失败。", ex);
                        return(CConstant.EXPORT_FAILURE);
                    }
                }
                return(CConstant.EXPORT_SUCCESS);
            }
            else
            {
                return(CConstant.EXPORT_CANCEL);
            }
            return(CConstant.EXPORT_SUCCESS);
        }
        public static bool ExportDataToExcel(System.Data.DataTable srcDataTable, string excelFilePath)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            object missing = System.Reflection.Missing.Value;

            //导出到execl
            try
            {
                if (xlApp == null)
                {
                    MessageBox.Show("无法创建Excel对象,可能您的电脑未安装Excel!");
                    return(false);
                }

                Microsoft.Office.Interop.Excel.Workbooks xlBooks = xlApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook  xlBook  = xlBooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Sheets[1];

                //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
                xlApp.Visible = false;

                object[,] objData = new object[srcDataTable.Rows.Count + 1, srcDataTable.Columns.Count];
                //首先将数据写入到一个二维数组中
                for (int i = 0; i < srcDataTable.Columns.Count; i++)
                {
                    objData[0, i] = srcDataTable.Columns[i].ColumnName;
                }
                if (srcDataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < srcDataTable.Rows.Count; i++)
                    {
                        for (int j = 0; j < srcDataTable.Columns.Count; j++)
                        {
                            objData[i + 1, j] = srcDataTable.Rows[i][j];
                        }
                    }
                }

                string startCol     = "A";
                int    iCnt         = (srcDataTable.Columns.Count / 26);
                string endColSignal = (iCnt == 0 ? "" : ((char)('A' + (iCnt - 1))).ToString());
                string endCol       = endColSignal + ((char)('A' + srcDataTable.Columns.Count - iCnt * 26 - 1)).ToString();
                Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(startCol + "1", endCol + (srcDataTable.Rows.Count - iCnt * 26 + 1).ToString());

                range.Value = objData;                                         //给Exccel中的Range整体赋值
                range.EntireColumn.AutoFit();                                  //设定Excel列宽度自适应
                xlSheet.get_Range(startCol + "1", endCol + "1").Font.Bold = 1; //Excel文件列名 字体设定为Bold

                //设置禁止弹出保存和覆盖的询问提示框
                xlApp.DisplayAlerts          = false;
                xlApp.AlertBeforeOverwriting = false;
                //if (File.Exists(excelFilePath))
                //    File.Delete(excelFilePath);

                if (xlSheet != null)
                {
                    xlSheet.SaveAs(excelFilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                    xlApp.Quit();
                    //KillProcess(xlApp);
                    //SystemUnit.KillProcess(xlApp);
                }
            }
            catch (Exception ex)
            {
                xlApp.Quit();
                //KillProcess(xlApp);
                //throw ex;
                return(false);
            }
            return(true);
        }
Пример #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            KillProcess("excel");
            OpenFileDialog oFile = new OpenFileDialog();

            oFile.Filter = @"Word文件(*.doc,*.docx)|*.doc;*.docx";
            if (oFile.ShowDialog() == DialogResult.OK)
            {
                object oFileName = oFile.FileName;
                //object oFileName = @"D:\图片\test.docx";
                object oReadOnly = true;
                object oMissing  = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Document   oDoc;
                Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = true;//只是为了方便观察
                oDoc          = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                string tableMessage = "";
                string tmp;
                string path = AppDomain.CurrentDomain.BaseDirectory + "生成的excel文件";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string oExcelName = path + "\\" + "生成的excel" + ".xlsx";
                object oRead      = false;
                object oMiss      = System.Reflection.Missing.Value;
                var    oExcel     = new Microsoft.Office.Interop.Excel.Application();
                //Microsoft.Office.Interop.Excel.Workbook xBook = oExcel.Workbooks.Open(oExcelName, oMiss, oRead, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss,oMiss, oMiss, oMiss);
                Microsoft.Office.Interop.Excel.Workbook xBook = oExcel.Workbooks.Add(Type.Missing);

                Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xBook.ActiveSheet;
                //Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets.get_Item(oDoc.Tables.Count);
                // Microsoft.Office.Interop.Excel._Worksheet xSt1 = (Microsoft.Office.Interop.Excel._Worksheet)xBook.Sheets.Add(Missing.Value, ws, Missing.Value, Missing.Value);
                if (oDoc.Tables.Count <= 0)
                {
                    return;
                }
                if (oDoc.Tables.Count > 1)
                {
                    ws = xBook.Sheets.Add(Missing.Value, ws, oDoc.Tables.Count - 1, Missing.Value);
                }

                Microsoft.Office.Interop.Excel.Sheets shs = oExcel.Sheets;
                for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
                {
                    if (oDoc.Tables.Count <= 1)
                    {
                    }
                    else
                    {
                        ws = xBook.Sheets[tablePos];;
                    }
                    Microsoft.Office.Interop.Word.Table nowTable = oDoc.Tables[tablePos];
                    int n = oDoc.Tables[tablePos].Rows.Count;
                    for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
                    {
                        for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
                        {
                            Microsoft.Office.Interop.Excel.Range rang = (Microsoft.Office.Interop.Excel.Range)ws.Cells[rowPos, columPos];
                            //if ((bool)rang.MergeCells==false)
                            //{
                            tableMessage = nowTable.Cell(rowPos, columPos).Range.Text.Trim();
                            tmp          = tableMessage.Replace("\r\a", "");
                            ws.Cells[rowPos, columPos] = tmp;
                            //}
                        }
                    }
                }
                ws.SaveAs(oExcelName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                MessageBox.Show(oExcelName + @"已成功生成" + oDoc.Tables.Count.ToString() + @"个表格");
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                oExcel.Quit();
            }
        }
Пример #25
0
        /// <summary>
        /// 导出文本
        /// </summary>
        private void ExoprtText()
        {
            Microsoft.Office.Interop.Excel.Workbook  xBook       = null;
            Microsoft.Office.Interop.Excel.Worksheet xSheet      = null;
            Microsoft.Office.Interop.Excel.Worksheet beforeSheet = null;

            // 设定保存的文件名
            string fileName = this.baseFile;

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = @"TextExport.xlsx";
            }

            // 先删除原来的文件
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            // 显示进度条
            this.ResetProcessBar(this.textFiles.Count);

            try
            {
                // 创建Application对象
                this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

                // 追加一个WorkBook
                xBook = this.xApp.Workbooks.Add(Missing.Value);

                for (int j = 0; j < this.textFiles.Count; j++)
                {
                    // 追加一个Sheet
                    FilePosInfo filePosInfo = this.textFiles[j];

                    string jpText = string.Empty;
                    string cnText = string.Empty;

                    this.Invoke((MethodInvoker) delegate()
                    {
                        // 更新当前文本
                        this.fileList.SelectedIndex = j;

                        // 取得日文、中文文本
                        jpText = this.txtJp.Text;
                        cnText = this.txtCn.Text;
                    });

                    // 设置当前Sheet名(如果有重复的就累加编号)
                    string sheetName     = Util.GetShortFileName(filePosInfo.File);
                    int    sameNameCount = 0;
                    for (int i = 0; i < j; i++)
                    {
                        if (Util.GetShortFileName(this.textFiles[i].File).IndexOf(sheetName) >= 0)
                        {
                            sameNameCount++;
                        }
                    }

                    if (beforeSheet == null)
                    {
                        xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    }
                    else
                    {
                        xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets.Add(beforeSheet, Missing.Value, Missing.Value, Missing.Value);
                    }
                    xSheet.Name = sheetName + (sameNameCount > 0 ? "_" + sameNameCount.ToString() : string.Empty);
                    beforeSheet = xSheet;

                    // 将每行文本保存到Sheet中
                    string[] jpTexts = jpText.Split('\n');
                    string[] cnTexts = cnText.Split('\n');

                    for (int i = 0; i < jpTexts.Length; i++)
                    {
                        // 写入日文文本
                        Microsoft.Office.Interop.Excel.Range rngJp = xSheet.get_Range("A" + (i + 1), Missing.Value);
                        rngJp.Value2 = jpTexts[i];
                    }
                    for (int i = 0; i < cnTexts.Length; i++)
                    {
                        // 写入中文文本
                        Microsoft.Office.Interop.Excel.Range rngCn = xSheet.get_Range("G" + (i + 1), Missing.Value);
                        rngCn.Value2 = cnTexts[i];
                    }

                    // 更新进度条
                    this.ProcessBarStep();
                }
            }
            finally
            {
                // 保存
                xSheet.SaveAs(
                    fileName,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 隐藏进度条
                this.CloseProcessBar();

                // 清空各种对象
                xSheet = null;
                xBook  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }

                // 显示保存完成信息
                MessageBox.Show("导出完成!");
            }
        }
Пример #26
0
        /// <summary>
        /// Skp的中文文本追加0
        /// </summary>
        private void AddCnSkpTxtZero()
        {
            Microsoft.Office.Interop.Excel.Workbook  xBook  = null;
            Microsoft.Office.Interop.Excel.Worksheet xSheet = null;

            try
            {
                // 创建Application对象
                this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

                // 得到WorkBook对象, 打开已有的文件
                xBook = this.xApp.Workbooks._Open(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\chtTextCnEnMap2.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 显示进度条
                this.ResetProcessBar(xBook.Sheets.Count);

                for (int i = xBook.Sheets.Count; i >= 1; i--)
                {
                    // 取得相应的Sheet
                    xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[i];
                    for (int j = 1; j < 50; j++)
                    {
                        Microsoft.Office.Interop.Excel.Range rngCn = xSheet.get_Range("L" + j, Missing.Value);
                        if (rngCn != null && rngCn.Value2 != null && !string.IsNullOrEmpty(rngCn.Value2 as string))
                        {
                            rngCn.Value2 = rngCn.Value2 + "^0^";
                        }
                    }

                    // 更新进度条
                    this.ProcessBarStep();
                }

                // 隐藏进度条
                this.CloseProcessBar();

                // 保存
                xSheet.SaveAs(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\chtTextCnEnMap3.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            }
            catch (Exception me)
            {
                MessageBox.Show(me.Message);
            }
            finally
            {
                // 隐藏进度条
                this.CloseProcessBar();

                // 清空各种对象
                xSheet = null;
                xBook  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }
            }
        }
Пример #27
0
        /// <summary>
        /// 复制Skp的中文文本
        /// </summary>
        private void CopyCnSkpTxt()
        {
            Microsoft.Office.Interop.Excel.Workbook  xBook  = null;
            Microsoft.Office.Interop.Excel.Worksheet xSheet = null;
            List <string> enSb = new List <string>();
            List <string> cnSb = new List <string>();
            Dictionary <string, List <string> > txtMap = new Dictionary <string, List <string> >();

            try
            {
                // 创建Application对象
                this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

                // 得到WorkBook对象, 打开已有的文件
                xBook = this.xApp.Workbooks._Open(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\TOS_skp.xls",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 取得相应的Sheet
                xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
                int lineNum = 1;
                while (lineNum < 3697)
                {
                    enSb.Add(xSheet.get_Range("B" + lineNum, Missing.Value).Value2 as string);
                    cnSb.Add(xSheet.get_Range("C" + lineNum, Missing.Value).Value2 as string);
                    lineNum++;
                }

                xSheet = null;
                xBook  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }

                //// 创建Application对象
                //this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                //xBook = this.xApp.Workbooks._Open(
                //   @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\chtText_En.xlsx",
                //   Missing.Value, Missing.Value, Missing.Value, Missing.Value
                //   , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                //   , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                //// 显示进度条
                //this.ResetProcessBar(xBook.Sheets.Count);

                //for (int i = xBook.Sheets.Count; i >= 1; i--)
                //{
                //    // 取得相应的Sheet
                //    xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[i];
                //    string enTxt = xSheet.get_Range("G1", Missing.Value).Value2 as string;
                //    if (string.IsNullOrEmpty(enTxt))
                //    {
                //        enTxt = string.Empty;
                //    }
                //    enTxt = enTxt.Replace("^0a^", "\n").Replace("^0^", string.Empty);

                //    for (int j = 0; j < enSb.Count; j++)
                //    {
                //        if (!string.IsNullOrEmpty(enSb[j]) && !string.IsNullOrEmpty(enTxt) && enSb[j].StartsWith(enTxt, StringComparison.OrdinalIgnoreCase))
                //        {
                //            List<string> cnItemSb = new List<string>();
                //            for (int k = j; k < j + 35 && k < cnSb.Count; k++)
                //            {
                //                cnItemSb.Add(cnSb[k]);
                //            }
                //            txtMap.Add(xSheet.Name, cnItemSb);
                //            break;
                //        }
                //    }

                //    // 更新进度条
                //    this.ProcessBarStep();
                //}

                //// 隐藏进度条
                //this.CloseProcessBar();

                //xSheet = null;
                //xBook = null;
                //if (this.xApp != null)
                //{
                //    this.xApp.Quit();
                //    this.xApp = null;
                //}

                // 创建Application对象
                this.xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                xBook     = this.xApp.Workbooks._Open(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\chtTextCnEnMap.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 显示进度条
                this.ResetProcessBar(xBook.Sheets.Count);

                for (int i = xBook.Sheets.Count; i >= 1; i--)
                {
                    // 取得相应的Sheet
                    xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[i];
                    Microsoft.Office.Interop.Excel.Range rngCn = xSheet.get_Range("L1", Missing.Value);
                    string line1Val = rngCn.Value2 as string;
                    rngCn = xSheet.get_Range("L2", Missing.Value);
                    string line2Val = rngCn.Value2 as string;
                    rngCn = xSheet.get_Range("L3", Missing.Value);
                    string line3Val = rngCn.Value2 as string;
                    rngCn = xSheet.get_Range("L4", Missing.Value);
                    string line4Val = rngCn.Value2 as string;
                    rngCn = xSheet.get_Range("L5", Missing.Value);
                    string line5Val = rngCn.Value2 as string;
                    int    lineNo   = -1;
                    if (!string.IsNullOrEmpty(line1Val) && string.IsNullOrEmpty(line2Val) && string.IsNullOrEmpty(line3Val) && string.IsNullOrEmpty(line4Val) && string.IsNullOrEmpty(line5Val))
                    {
                        lineNo = 1;
                    }
                    else if (string.IsNullOrEmpty(line1Val) && !string.IsNullOrEmpty(line2Val) && string.IsNullOrEmpty(line3Val) && string.IsNullOrEmpty(line4Val) && string.IsNullOrEmpty(line5Val))
                    {
                        lineNo = 2;
                    }
                    else if (string.IsNullOrEmpty(line1Val) && string.IsNullOrEmpty(line2Val) && !string.IsNullOrEmpty(line3Val) && string.IsNullOrEmpty(line4Val) && string.IsNullOrEmpty(line5Val))
                    {
                        lineNo = 3;
                    }
                    else if (string.IsNullOrEmpty(line1Val) && string.IsNullOrEmpty(line2Val) && string.IsNullOrEmpty(line3Val) && !string.IsNullOrEmpty(line4Val) && string.IsNullOrEmpty(line5Val))
                    {
                        lineNo = 4;
                    }
                    else if (string.IsNullOrEmpty(line1Val) && string.IsNullOrEmpty(line2Val) && string.IsNullOrEmpty(line3Val) && string.IsNullOrEmpty(line4Val) && !string.IsNullOrEmpty(line5Val))
                    {
                        lineNo = 5;
                    }

                    if (lineNo >= 0)
                    {
                        rngCn = xSheet.get_Range("L" + lineNo, Missing.Value);
                        string lineVal  = rngCn.Value2 as string;
                        int    linIndex = 1;
                        for (int j = 0; j < enSb.Count; j++)
                        {
                            if (!string.IsNullOrEmpty(enSb[j]) && enSb[j].IndexOf(lineVal) >= 0)
                            {
                                int startPos = j - lineNo + 1;
                                for (int k = startPos; k < startPos + 30; k++)
                                {
                                    rngCn        = xSheet.get_Range("L" + (linIndex++), Missing.Value);
                                    rngCn.Value2 = cnSb[k];
                                }
                                break;
                            }
                        }
                    }

                    // 更新进度条
                    this.ProcessBarStep();
                }

                // 隐藏进度条
                this.CloseProcessBar();

                // 保存
                xSheet.SaveAs(
                    @"E:\Study\MySelfProject\Hanhua\TodoCn\TalesOfSymphonia\chtTextCnEnMap2.xlsx",
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            }
            catch (Exception me)
            {
                MessageBox.Show(me.Message);
            }
            finally
            {
                // 隐藏进度条
                this.CloseProcessBar();

                // 清空各种对象
                xSheet = null;
                xBook  = null;
                if (this.xApp != null)
                {
                    this.xApp.Quit();
                    this.xApp = null;
                }
            }
        }
Пример #28
0
        //#region 导出全部数据到Excel中,可弹出保存对话框,但没用SaveFileDialog

        //public void printAll(System.Data.DataTable dt)
        //{
        //    //导出到execl
        //    try
        //    {
        //        //没有数据的话就不往下执行
        //        if (dt.Rows.Count == 0)
        //            return;
        //        //实例化一个Excel.Application对象
        //        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

        //        //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
        //        excel.Application.Workbooks.Add(true);

        //        //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
        //        excel.Visible = false;
        //        //生成Excel中列头名称
        //        for (int i = 0; i < dt.Columns.Count; i++)
        //        {
        //            excel.Cells[1, i + 1] = dgvList.Columns[i].HeaderText;//输出DataGridView列头名
        //        }

        //        //把DataGridView当前页的数据保存在Excel中
        //        if (dt.Rows.Count > 0)
        //        {
        //            for (int i = 0; i < dt.Rows.Count; i++)//控制Excel中行,上下的距离,就是可以到Excel最下的行数,比数据长了报错,比数据短了会显示不完
        //            {
        //                for (int j = 0; j < dt.Columns.Count; j++)//控制Excel中列,左右的距离,就是可以到Excel最右的列数,比数据长了报错,比数据短了会显示不完
        //                {
        //                    string str = dt.Rows[i][j].ToString();
        //                    excel.Cells[i + 2, j + 1] = "'" + str;//i控制行,从Excel中第2行开始输出第一行数据,j控制列,从Excel中第1列输出第1列数据,"'" +是以string形式保存,所以遇到数字不会转成16进制
        //                }
        //            }
        //        }
        //        //设置禁止弹出保存和覆盖的询问提示框
        //        excel.DisplayAlerts = false;
        //        excel.AlertBeforeOverwriting = false;

        //        //保存工作簿,值为false会报错
        //        excel.Application.Workbooks.Add(true).Save();
        //        //保存excel文件
        //        excel.Save("D:" + "\\KKHMD.xls");

        //        //确保Excel进程关闭
        //        excel.Quit();
        //        excel = null;

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "错误提示");
        //    }

        //}

        //#endregion

        //#region 将DataGridView控件中数据导出到Excel
        ///// <summary>
        ///// 将DataGridView控件中数据导出到Excel
        ///// </summary>
        ///// <param name="gridView">DataGridView对象</param>
        ///// <param name="isShowExcle">是否显示Excel界面</param>
        ///// <returns></returns>
        //public bool ExportDataGridview(DataGridView gridView, bool isShowExcle)
        //{
        //    if (gridView.Rows.Count == 0)
        //        return false;
        //    //建立Excel对象
        //    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        //    excel.Application.Workbooks.Add(true);
        //    excel.Visible = isShowExcle;
        //    //生成字段名称
        //    for (int i = 0; i < gridView.ColumnCount; i++)
        //    {
        //        excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
        //    }
        //    //填充数据
        //    for (int i = 0; i < gridView.RowCount - 1; i++)
        //    {
        //        for (int j = 0; j < gridView.ColumnCount; j++)
        //        {
        //            if (gridView[j, i].ValueType == typeof(string))
        //            {
        //                excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
        //            }
        //            else
        //            {
        //                excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
        //            }
        //        }
        //    }
        //    return true;
        //}
        //#endregion

        //#region 将所有数据导出到Excel:
        //private void GenerateExcelAll(System.Data.DataTable dt, DataGridView dgv)
        //{
        //    //导出到execl
        //    try
        //    {
        //        //没有数据的话就不往下执行
        //        if (dt.Rows.Count == 0)
        //        {
        //            MessageBox.Show("当前页面没有数据可以导出!", "导出结果", MessageBoxButtons.OK);
        //            return;
        //        }
        //        //实例化一个Excel.Application对象
        //        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        //        //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
        //        excel.Application.Workbooks.Add(true);
        //        //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
        //        excel.Visible = false;
        //        //生成Excel中列头名称
        //        //生成Excel中列头名称------------------------------**********************************---------------------------------------
        //        int columnCount = 0;
        //        for (int i = 0; i < dgv.Columns.Count; i++)
        //        {
        //            if (dgv.Columns[i].Visible)
        //            {
        //                columnCount = columnCount + 1;
        //            }
        //        }
        //        string[] headers = new string[columnCount];
        //        int index = 0;
        //        for (int i = 0; i < dgv.Columns.Count; i++)
        //        {
        //            if (dgv.Columns[i].Visible)
        //            {
        //                headers[index] = dgv.Columns[i].HeaderText;
        //                index = index + 1;
        //            }
        //        }
        //        for (int i = 0; i < columnCount; i++)
        //        {
        //            excel.Cells[1, i + 1] = headers[i];
        //            //if (dgv.Columns[i].ValueType == typeof(DateTime))
        //            //{
        //            //    Microsoft.Office.Interop.Excel.Range headRange = excel.Cells[1, i - 1] as Microsoft.Office.Interop.Excel.Range;// as Range;//获取表头单元格
        //            //    headRange.ColumnWidth = 22;//设置列宽
        //            //}
        //        }
        //        //---------------------------------------------------**********************************----------------------------------------
        //        ////////----------------------------------------**************************************---------------------------------------------
        //        //把DataGridView当前页的数据保存在Excel中
        //        if (dt.Rows.Count > 0)
        //        {
        //            int ccc = dgv.Columns.Count;
        //            for (int i = 0; i < dt.Rows.Count; i++)//控制Excel中行,上下的距离,就是可以到Excel最下的行数,比数据长了报错,比数据短了会显示不完
        //            {
        //                int columnIndex = 0;
        //                for (int j = 0; j < dt.Columns.Count; j++)//控制Excel中列,左右的距离,就是可以到Excel最右的列数,比数据长了报错,比数据短了会显示不完
        //                {
        //                    if (dgv.Columns[j].Visible)
        //                    {
        //                        columnIndex = columnIndex + 1;
        //                        string str = dt.Rows[i][j].ToString();
        //                        excel.Cells[i + 2, columnIndex] = "'" + str;//i控制行,从Excel中第2行开始输出第一行数据,j控制列,从Excel中第1列输出第1列数据,"'" +是以string形式保存,所以遇到数字不会转成16进制
        //                    }
        //                }
        //            }
        //        }
        //        //设置禁止弹出保存和覆盖的询问提示框
        //        excel.DisplayAlerts = false;
        //        excel.AlertBeforeOverwriting = false;
        //        //保存工作簿,值为false会报错
        //        //excel.Application.Workbooks.Add(false);//.Save();
        //        //确保Excel进程关闭
        //        excel.Save();
        //        excel.Quit();
        //        excel = null;
        //        MessageBox.Show("您所查询的所有数据已经成功导出到您指定的目录!", "导出结果", MessageBoxButtons.OK);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "错误提示");
        //    }
        //}
        //#endregion

        #endregion

        /// <summary>

        /// 另存新档按钮   导出成Excel

        /// </summary>

        private void SaveToExcel() //另存新档按钮   导出成Excel
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";

            saveFileDialog.FilterIndex = 0;

            saveFileDialog.RestoreDirectory = true;

            saveFileDialog.CreatePrompt = true;

            saveFileDialog.Title = "Export Excel File To";


            saveFileDialog.ShowDialog();

            string strName = saveFileDialog.FileName;

            if (string.IsNullOrEmpty(strName))
            {
                return;
            }

            System.Reflection.Missing miss = System.Reflection.Missing.Value;


            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();

            Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;

            Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));

            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;

            sheet.Name = "test";


            int colIndex = 0;

            foreach (DataGridViewColumn column in dgvList.Columns)
            {
                colIndex++;

                excel.Cells[1, colIndex] = column.HeaderText;
            }


            for (int i = 0; i < dgvList.Rows.Count; i++)
            {
                for (int j = 0; j < dgvList.Columns.Count; j++)
                {
                    if (dgvList.Columns[j].Name == "IdCard")
                    {
                        excel.Cells[i + 2, j + 1] = "'" + dgvList.Rows[i].Cells[j].Value.ToString();
                    }
                    else
                    {
                        excel.Cells[i + 2, j + 1] = dgvList.Rows[i].Cells[j].Value.ToString();
                    }
                }
            }



            sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss);



            book.Close(false, miss, miss);

            books.Close();

            excel.Quit();


            //System.Runtime.InteropServices.Marshal.ReleaseComObject();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(book);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(books);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

            GC.Collect();
        }
Пример #29
0
        private void CreaExcel(DataSet ds)
        {
            Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbooks oLibros = default(Microsoft.Office.Interop.Excel.Workbooks);
            Microsoft.Office.Interop.Excel.Workbook  oLibro  = default(Microsoft.Office.Interop.Excel.Workbook);

            Microsoft.Office.Interop.Excel.Sheets oHojas = default(Microsoft.Office.Interop.Excel.Sheets);

            Microsoft.Office.Interop.Excel.Worksheet oHoja = default(Microsoft.Office.Interop.Excel.Worksheet);


            Microsoft.Office.Interop.Excel.Range oCeldas = default(Microsoft.Office.Interop.Excel.Range);

            try
            {
                string sFile     = null;
                string sTemplate = null;

                // Usamos una plantilla para crear el nuevo excel

                sFile = Server.MapPath("PDV_Planning") + "\\" + "Datos_Panel_ptoVenta2.xls";

                sTemplate = Server.MapPath("PDV_Planning") + "\\" + "Datos_Panel_ptoVenta1.xls";

                oExcel.Visible = false;

                oExcel.DisplayAlerts = false;

                // Abrimos un nuevo libro

                oLibros = oExcel.Workbooks;

                oLibros.Open(sTemplate);

                oLibro = oLibros.Item[1];

                oHojas = oLibro.Worksheets;


                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    oHoja = (Microsoft.Office.Interop.Excel.Worksheet)oHojas.Item[i + 1];

                    oHoja.Name = "Hoja" + (i + 1);

                    oCeldas = oHoja.Cells;
                    oHoja.Range["B2"].Interior.Color = 0;
                    oHoja.Range["B2"].Font.Color     = 16777215;
                    oHoja.Range["A2"].Interior.Color = 0;
                    oHoja.Range["A2"].Font.Color     = 16777215;


                    oHoja.Range["B2"].Font.Bold = true;
                    oHoja.Range["A2"].Font.Bold = true;

                    oHoja.Range["A2", "B" + (ds.Tables[i].Rows.Count + 2).ToString()].Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlDash;
                    oHoja.Range["A2", "B" + (ds.Tables[i].Rows.Count + 2).ToString()].Borders.LineStyle = Microsoft.Office.Interop.Excel.XlBorderWeight.xlHairline;

                    VuelcaDatos(ds.Tables[i], oCeldas);
                }

                oHoja.SaveAs(sFile);

                oLibro.Close();

                // Eliminamos lo que hemos creado

                oExcel.Quit();

                oExcel = null;

                oLibros = null;

                oLibro = null;

                oHojas = null;

                oHoja = null;

                oCeldas = null;

                System.GC.Collect();
            }
            catch
            {
                oLibro.Close();
                oExcel.Quit();

                Pmensaje.CssClass      = "MensajesSupervisor";
                lblencabezado.Text     = "Sr. Usuario";
                lblmensajegeneral.Text = "Es indispensable que cierre sesión he inicie nuevamente. su sesión expiró.";
                Mensajes_Usuario();
            }
        }
Пример #30
0
        /// <summary>
        /// 导出文本
        /// </summary>
        private void ExoprtText()
        {
            Microsoft.Office.Interop.Excel.Application xApp   = null;
            Microsoft.Office.Interop.Excel.Workbook    xBook  = null;
            Microsoft.Office.Interop.Excel.Worksheet   xSheet = null;

            // 设定保存的文件名
            string fileName = @"E:\My\Hanhua\testFile\bioCv\BioCvTextNgc.xls";

            //string fileName = @"D:\game\iso\wii\生化危机维罗妮卡汉化\Bio0Text_" + this.exportName + ".xls";

            // 先删除原来的文件
            File.Delete(fileName);

            // 显示进度条
            this.ResetProcessBar(this.fileList.Items.Count);

            try
            {
                // 创建Application对象
                xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                //xApp.Visible = true;

                // 追加一个WorkBook
                xBook = xApp.Workbooks.Add(Missing.Value);

                for (int j = 0; j < this.fileList.Items.Count; j++)
                {
                    // 追加一个Sheet
                    FilePosInfo filePosInfo = this.textFiles[j];

                    // 更新当前文本
                    this.fileList.SelectedIndex = j;

                    // 取得日文、中文文本
                    string jpText = this.txtJp.Text;
                    string cnText = this.txtCn.Text;

                    string sheetName     = Util.GetShortFileName(filePosInfo.File);
                    int    sameNameCount = 0;
                    for (int i = 0; i < j; i++)
                    {
                        if (Util.GetShortFileName(this.textFiles[i].File).IndexOf(sheetName) >= 0)
                        {
                            sameNameCount++;
                        }
                    }

                    xSheet      = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    xSheet.Name = sheetName + (sameNameCount > 0 ? "_" + sameNameCount.ToString().PadLeft(2, '0') : string.Empty);

                    // 将每行文本保存到Sheet中
                    string[] jpTexts = jpText.Split('\n');
                    string[] cnTexts = cnText.Split('\n');

                    for (int i = 0; i < jpTexts.Length; i++)
                    {
                        // 写入日文文本
                        Microsoft.Office.Interop.Excel.Range rngJp = xSheet.get_Range("A" + (i + 1), Missing.Value);
                        rngJp.Value2 = jpTexts[i];
                    }
                    for (int i = 0; i < cnTexts.Length; i++)
                    {
                        // 写入中文文本
                        Microsoft.Office.Interop.Excel.Range rngCn = xSheet.get_Range("G" + (i + 1), Missing.Value);
                        rngCn.Value2 = cnTexts[i];
                    }

                    // 更新进度条
                    this.ProcessBarStep();
                }

                // 保存
                xSheet.SaveAs(
                    fileName,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // 隐藏进度条
                this.CloseProcessBar();

                // 显示保存完成信息
                MessageBox.Show("导出完成!");
            }
            catch (Exception me)
            {
                MessageBox.Show(this.baseFile + "\n" + me.Message);
            }
            finally
            {
                // 隐藏进度条
                this.CloseProcessBar();

                // 清空各种对象
                xSheet = null;
                xBook  = null;
                if (xApp != null)
                {
                    xApp.Quit();
                    xApp = null;
                }
            }
        }