拷贝既存excel文件sheet方法

此代码示例展示了如何使用VBA批量复制并填充EXCEL模板中的特定工作表,并进行数据填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop

------------------------------------------------------------    

''' <summary>

    ''' EXCELファイルにテンプレートシートをコピーする
    ''' </summary>
    ''' <param name="sheetCnt">コピーシート数</param>
    ''' <remarks></remarks>
    Private Sub CopyExcelSheet(ByVal sheetCnt As Integer)
        Dim xlApp As Object
        xlApp = CreateObject("Excel.Application")

        Dim xlBooks As Object = xlApp.Workbooks

        ' fn:excel文件路径c:\xxx\aaa.xls

        Dim xlBook As Object = xlBooks.Open(fn)
        Dim xlSheet As Object = xlBook.Sheets

        Try
            xlBook = xlApp.Workbooks.Open(fn)
            xlApp.Visible = True
            xlApp.Displayalerts = False
            'xlSheet = xlBook.Worksheets(1)

            ' シートコピー
            Dim indexNew As Integer = 0
            Dim sheet2Index As Integer = 0
            For index As Integer = 0 To sheetCnt - 1
                xlSheet = xlBook.Worksheets(1)
                If index = 0 Then
                    indexNew = index
                End If
                If indexNew <= arr.Count - 1 Then
                    ' シートコピー1から
                    If index = 0 Then
                        xlSheet.Copy(After:=xlBook.Worksheets(2 + index))
                    Else
                        'xlSheet.Copy(After:=xlBook.Worksheets(2 + index + 1))
                        xlSheet.Copy(After:=xlBook.Worksheets(sheet2Index))
                    End If


                    ' シート選択0から
                    If index = 0 Then
                        xlSheet = xlBook.Worksheets(3 + index)
                    Else
                        xlSheet = xlBook.Worksheets(sheet2Index + 1)
                    End If
                    ' セル書く
                    Dim lineData As String() = arr(indexNew).ToString.Split(",")
                    '  郵便番号 
                    xlSheet.Cells(5, 41) = lineData(0)
                    '  住所
                    xlSheet.Cells(7, 41) = lineData(1)
                    ' 氏名
                    xlSheet.Cells(3, 41) = lineData(2)
                    If indexNew <= arr.Count - 2 Then
                        Dim lineData2 As String() = arr(indexNew + 1).ToString.Split(",")
                        ' 郵便番号 
                        xlSheet.Cells(35, 41) = lineData2(0)
                        ' 住所
                        xlSheet.Cells(37, 41) = lineData2(1)
                        ' 氏名
                        xlSheet.Cells(33, 41) = lineData2(2)
                    End If


                    ' シート2をコピー
                    xlSheet = xlBook.Worksheets(2)
                    If index = 0 Then
                        xlSheet.Copy(After:=xlBook.Worksheets(2 + index + 1))
                        sheet2Index = 2 + index + 1
                    Else
                        'xlSheet.Copy(After:=xlBook.Worksheets(2 + index + 2))
                        sheet2Index = sheet2Index + 1
                        xlSheet.Copy(After:=xlBook.Worksheets(sheet2Index))
                    End If
                    ' シート2にデータを書くTODO...
                End If


                'sheet2Index = 2 + index + 2
                sheet2Index = sheet2Index + 1
                indexNew = indexNew + 2
            Next
            '' テンプレートシートを削除
     'TODO

        Catch ex As Exception
            labOperStates.Visible = False
            MessageBox.Show("シートコピー中、エラー...")
        Finally
            If Not xlSheet Is Nothing Then
                Try
                Finally
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
                End Try
            End If


            If Not xlBook Is Nothing Then
                Try
                    xlBook.Close()
                Finally
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
                End Try
            End If


            If Not xlBooks Is Nothing Then
                Try
                Finally
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
                End Try
            End If
            If Not xlApp Is Nothing Then
                Try
                    xlApp.Quit()
                Finally
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
                End Try
            End If
            'System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
            'System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
            'System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
            'xlBook.Close(True)
            'xlApp.Quit()
            'xlApp = Nothing


        End Try
    End Sub
当你需要保留原始Excel文件中的数值和格式,包括货币、日期、百分比等格式,以及特殊样式如颜色和边框,使用Apache POI库可以做到这一点。以下是一个示例,展示了如何在复制工作表时保持这些特性: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.ss.util.CellRangeAddress; public void copyWithFormat(Sheet sourceSheet, XSSFSheet destinationSheet) throws IOException { // 1. 遍历源工作表的所有行 for (int rowIndex = 0; rowIndex < sourceSheet.getLastRowNum() + 1; rowIndex++) { Row sourceRow = sourceSheet.getRow(rowIndex); if (sourceRow == null) continue; // 跳过空行 // 2. 复制行 Row destinationRow = destinationSheet.createRow(rowIndex); int cellCount = sourceRow.getLastCellNum(); // 3. 复制单元格,并保持格式 for (int colIndex = 0; colIndex < cellCount; colIndex++) { Cell sourceCell = sourceRow.getCell(colIndex); Cell destinationCell = destinationRow.createCell(colIndex); // 如果源细胞有格式 if (sourceCell.getCellType() != Cell.CELL_TYPE_BLANK && sourceCell.getCellStyle() != null) { CellStyle style = sourceCell.getCellStyle(); destinationCell.setCellStyle(style); // 复制格式属性(比如数字格式、字体、颜色等) Font font = style.getFont(); destinationCell.getSheet().getWorkbook().createFont().setAttributes(font.getAttributes()); destinationCell.getSheet().getWorkbook().createFont().setName(font.getName()); // 如果是数字格式(包括货币、日期、百分比),应用正确的格式 if (style.getDataFormat() != null) { DataFormatter formatter = new DataFormatter(); destinationCell.setCellType(CellType.NUMERIC); destinationCell.setCellValue(formatter.formatCellValue(sourceCell, style.getDataFormat())); } else if (sourceCell.getCellType() == CellType.FORMULA) { destinationCell.setCellFormula(sourceCell.getCellFormula()); } } // 如果源单元格包含值 if (!sourceCell.isEmpty()) { destinationCell.setCellValue(sourceCell.getCellValue()); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值