您可以使用EPPlus 创建一个受密码保护(锁定)的可以读取但不能编辑的excel 文件。我可以告诉你如何从这样的情况开始:
并获得这样的受保护文件:
首先,您必须下载 EPPlus Library 并将其包含在您的项目中。不要忘记查看伟大的EPPlusSamples Project
然后您需要一种方法来提取您的 DataGridView VISIBLE 数据(您不希望导出不可见的列)。我使用二维数组完成了它。这个函数接受一个DataGridView 参数并返回一个二维数组:
Function GetDataGridView2DArray(ByVal dataGridView As DataGridView) As String(,)
'Save list of visible columns
Dim nrVisibleColumns = (From c As DataGridViewColumn In DataGridView1.Columns
Where c.Visible
Select c).ToList()
'create 2d-array to store values, dimensions given by number of rows and visible columns
Dim dgvArray(nrVisibleColumns.Count, DataGridView1.Rows.Count) As String
'create the first row with Column Headers text
For Each col As DataGridViewColumn In nrVisibleColumns
dgvArray(col.Index + 1, 0) = col.HeaderText
Next
'create Rows, including Row Header text
For Each row As DataGridViewRow In DataGridView1.Rows
Dim rowNumber = row.Index + 1
dgvArray(0, rowNumber) = DataGridView1.Rows(row.Index).HeaderCell.Value 'save rowheader cell value
For Each col As DataGridViewColumn In nrVisibleColumns
dgvArray(col.Index + 1, rowNumber) = DataGridView1(col.Index, row.Index).Value
Next
Next
Return dgvArray
End Function
现在您已经有了数组,您可以创建一个 Excel 文件 并用数据填充它。另外,在保存之前,我们会用密码锁定它以防止用户编辑。
Private Sub CreateXls()
Dim fi = New FileInfo("C:\temp\output.xlsx")
Dim package As New ExcelPackage()
Dim ws = package.Workbook.Worksheets.Add("Dgv Output") 'create sheet
'get array of datagridview data
Dim dataArray = GetDataGridView2DArray(DataGridView1)
'loop my 2d array and fill my excel file
For iColumn As Integer = dataArray.GetLowerBound(0) To dataArray.GetUpperBound(0)
For iRow As Integer = dataArray.GetLowerBound(1) To dataArray.GetUpperBound(1)
ws.Cells(iRow + 1, iColumn + 1).Value = dataArray(iColumn, iRow)
ws.Cells(iRow + 1, iColumn + 1).Style.Locked = True 'lock the cell
Next
Next
ws.Cells.AutoFitColumns() 'resize columns to fit
ws.Protection.AllowFormatColumns = True 'let user resize columns if he wants
ws.Protection.SetPassword("1") 'protect the sheet from editing
package.SaveAs(fi) 'save file
End Sub
现在您应该可以一键轻松导出动态DataGridView了。