将带有 Worksheet.SaveAs 的 excel 文件保存到任何/选定的目录

Posted

技术标签:

【中文标题】将带有 Worksheet.SaveAs 的 excel 文件保存到任何/选定的目录【英文标题】:Save excel file with Worksheet.SaveAs to any/selected directory 【发布时间】:2018-06-24 10:46:14 【问题描述】:

我已经知道如何将我的 excel 文件保存到指定目录,但是当SaveFileDialog 框打开时,我希望能够保存在我想要的任何地方。我该怎么做?

private void btnExcellExport_Click(object sender, EventArgs e)
    
        if (!(dataGridView1.RowCount == 0))
        
            if (backgroundWorker1.IsBusy)
                return;
            using (SaveFileDialog sfd = new SaveFileDialog()  Filter = "Excel Workbook|*.xlsx", RestoreDirectory = true, InitialDirectory = HelpMeClass.GetExcelDirectory
        )
            
                sfd.FileName = HelpMeClass.SearchString;
                if (sfd.ShowDialog() == DialogResult.OK)
                
                    progressBar1.Show();
                    progressBar1.Minimum = 0;
                    progressBar1.Value = 0;
                    backgroundWorker1.RunWorkerAsync();

                
            
        
        else
        
            MessageBox.Show("Oops! Nothing to export!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        
    

后台工作人员:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)excel.ActiveSheet;

        excel.Visible = true;
        int index = 0;

        int process = dataGridView1.Rows.Count;
        int process1 = dataGridView2.Rows.Count;
        int process2 = dataGridView3.Rows.Count;



        ws.get_Range("A1", "C1").Merge(); // Merge columns for header
        ws.Cells[1, 1] = "Keyword: " + HelpMeClass.SearchString;
        ws.Cells[1, 1].Font.Bold = true; // Bold font in header


        if (!backgroundWorker1.CancellationPending)
        
            foreach (DataGridViewRow row in dataGridView1.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 1] = cell.Value;
                
            

            index = 0;
            foreach (DataGridViewRow row in dataGridView2.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process1);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 2] = cell.Value;
                
            

            index = 0;
            foreach (DataGridViewRow row in dataGridView3.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process2);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 3] = cell.Value;
                
            
        

        ws.Columns.AutoFit();



        try
        
            ws.SaveAs(Path.Combine(HelpMeClass.GetExcelDirectory, HelpMeClass.SearchString), XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
        
        catch (Exception ex)
        
            MessageBox.Show("Ooops! I can`t access the file. Make sure the excel file is closed and try again. " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            return;
        

        //excel.Quit();

    

InitialDirectory 获得了public string GetExcelDirectory get; = @"C:\Users\" + Environment.UserName + @"\Desktop\"; 的路径字符串,我希望有机会将文件保存在我想要的任何位置。

同样在SaveAs 语句中,我将此路径与文件名组合在一起。

【问题讨论】:

发帖前有没有搜索过答案?请参阅***.com/q/33411063/4961700 和给出的答案... 【参考方案1】:

我改用了这种方法。我已经使用Path.GetFirectoryName(sfd.FileName); 保存了选定的路径。然后是我通过该目录并结合文件名的 SaveAs。这完美无缺。

private void btnExcellExport_Click(object sender, EventArgs e)
    
        if (!(dataGridView1.RowCount == 0))
        
            if (backgroundWorker1.IsBusy)
                return;
            using (SaveFileDialog sfd = new SaveFileDialog()  Filter = "Excel Workbook|*.xlsx", RestoreDirectory = true, InitialDirectory = HelpMeClass.ExcelSaveDirectory
            )
            

                sfd.FileName = HelpMeClass.SearchString;

                if (sfd.ShowDialog() == DialogResult.OK)
                
                    HelpMeClass.ExcelSaveDirectory = Path.GetDirectoryName(sfd.FileName);
                    progressBar1.Show();
                    progressBar1.Minimum = 0;
                    progressBar1.Value = 0;
                    backgroundWorker1.RunWorkerAsync();

                
            
        
        else
        
            MessageBox.Show("Oops! Nothing to export!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        
    



private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)excel.ActiveSheet;

        excel.Visible = true;
        int index = 0;

        int process = dataGridView1.Rows.Count;
        int process1 = dataGridView2.Rows.Count;
        int process2 = dataGridView3.Rows.Count;



        ws.get_Range("A1", "C1").Merge(); // Merge columns for header
        ws.Cells[1, 1] = "Keyword: " + HelpMeClass.SearchString;
        ws.Cells[1, 1].Font.Bold = true; // Bold font in header


        if (!backgroundWorker1.CancellationPending)
        
            foreach (DataGridViewRow row in dataGridView1.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 1] = cell.Value;
                
            

            index = 0;
            foreach (DataGridViewRow row in dataGridView2.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process1);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 2] = cell.Value;
                
            

            index = 0;
            foreach (DataGridViewRow row in dataGridView3.Rows)
            
                backgroundWorker1.ReportProgress(index++ * 100 / process2);

                foreach (DataGridViewCell cell in row.Cells)
                
                    ws.Cells[index + 1, 3] = cell.Value;
                
            
        

        ws.Columns.AutoFit();



        try
        
            ws.SaveAs(Path.Combine(HelpMeClass.ExcelSaveDirectory, HelpMeClass.SearchString), XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
        
        catch (Exception ex)
        
            MessageBox.Show("Ooops! I can`t access the file. Make sure the excel file is closed and try again. " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            return;
        

        //excel.Quit();

    

【讨论】:

以上是关于将带有 Worksheet.SaveAs 的 excel 文件保存到任何/选定的目录的主要内容,如果未能解决你的问题,请参考以下文章

带有极坐标的动画图

DLIB:带有 halen 数据集的 194 个地标的 train_shape_predictor_ex.exe 给出运行时错误:分配错误

使用带有 ATA_PASS_THROUGH_EX 的 DeviceIoControl() 的 SECURITY_SET_PASSWORD 失败

响应按钮-带有名称和编号

春季启动数据休息中的日期问题

具有 LVS_EX_CHECKBOXES 样式的 CListCtrl