我正在使用 EPPus-LGPL 来编辑和下载 Excel。 但我总是发现文件被阻止;我需要转到属性,然后取消阻止文件以始终打开。我尝试使用代码解锁,但不起作用。 所以请给我解决方案来解锁 Excel 的代码。
单击按钮下载 Excel
Protected Sub btnExcell_Click(sender As Object, e As EventArgs) Handles btnExcell.Click
Try
Dim year As String = ""
Dim month As String = ""
Dim selectedYear As Integer = Convert.ToInt32(ddlYear.SelectedValue)
Dim selectedMonth As Integer = Convert.ToInt32(ddlMonth.SelectedValue)
year = selectedYear
month = selectedMonth
If String.IsNullOrEmpty(year) Then
year = ""
End If
If String.IsNullOrEmpty(month) Then
month = ""
End If
' Parse year and month
'Dim selectedYear As Integer = Convert.ToInt32(year)
'Dim selectedMonth As Integer = DateTime.ParseExact(month, "MMMM", System.Globalization.CultureInfo.CurrentCulture).Month
' Calculate StartDate and EndDate
Dim startDate As New DateTime(selectedYear, selectedMonth, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1) ' Last day of the month
Dim monthName As String = startDate.ToString("MMMM", CultureInfo.InvariantCulture)
Dim centralBankReport As New CentralBankReportVM()
centralBankReport = PopulateCentralBankReport(startDate, endDate)
' Path to the original Excel file
Dim originalFilePath As String = Server.MapPath("~/Files/CentralBankReport/sample.xlsx")
Using package As New OfficeOpenXml.ExcelPackage(New FileInfo(originalFilePath))
'Dim worksheet As OfficeOpenXml.ExcelWorksheet = package.Workbook.Worksheets("central_bank_of_somalia_Demo.xlsx") ' Replace "Sheet1" with the actual name of your worksheet
Dim worksheet = package.Workbook.Worksheets(1)
'Dim worksheet = package.Workbook.Worksheets("central_bank_of_somalia_Demo.xlsx")
' Modify individual cells
worksheet.Cells("F20").Value = year
worksheet.Cells("L20").Value = monthName
worksheet.Cells("F55").Value = "$" & centralBankReport.TotalUSDToSO
worksheet.Cells("I55").Value = "$" & centralBankReport.TotalUSDFrSO
worksheet.Cells("F69").Value = "$0.00"
worksheet.Cells("L69").Value = "$" & centralBankReport.OtherExpense
worksheet.Cells("F75").Value = "$0.00"
worksheet.Cells("L75").Value = "$0.00"
worksheet.Cells("K43").Value = DateTime.Now.ToString("dd-MMM-yyyy")
package.Save()
UnblockFile(originalFilePath)
' Prepare the modified Excel file for download
Dim fileBytes As Byte() = File.ReadAllBytes(originalFilePath)
Dim fileName As String = "sample_" & DateTime.Now.ToString("yyyyMMdd_HHmmss") & ".xlsx"
' Set the content type and headers
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.Buffer = True
' Response.AddHeader("content-disposition", "attachment;filename=" & fileName)
' Response.BinaryWrite(fileBytes)
Response.AddHeader(
"content-disposition", String.Format(CultureInfo.InvariantCulture, "attachment; filename={0}", fileName))
Response.BinaryWrite(package.GetAsByteArray())
Response.End()
End Using
Catch ex As Exception
Dim message As String = ex.Message
Response.Write("An error occurred while processing the request.")
End Try
End Sub
解锁功能目前有:
Private Sub UnblockFile(filePath As String)
Try
' Use PowerShell to unblock the file
Dim powerShellCommand As String = "Unblock-File -Path """ & filePath & """"
Dim processInfo As New ProcessStartInfo("powershell.exe", "-ExecutionPolicy Bypass -Command """ & powerShellCommand & """")
processInfo.CreateNoWindow = True
processInfo.UseShellExecute = False
processInfo.RedirectStandardOutput = True
Using process As New Process()
process.StartInfo = processInfo
process.Start()
process.WaitForExit()
End Using
Catch ex As Exception
' Log or display the exception message for debugging
Response.Write("An error occurred while unblocking the file: " & ex.Message)
End Try
End Sub
提前致谢。
在您尝试打开文件时,与原始文件相关的流似乎没有关闭。
您将
End Using
移动到 package.Save()
线之后。
然后更换
Response.BinaryWrite(package.GetAsByteArray())
行经
Response.BinaryWrite(File.ReadAllBytes(originalFilePath))