我在下面发布了一个 Excel 导出类的代码(无论如何,大部分都是)。我遇到的问题是这种导出在注入攻击时并不安全。我可以很容易地用参数屏蔽初始命令,但是,当我将参数化命令传递给 Export(string) 方法时,它会丢失以前在参数中设置的值;它只传递文字字符串(即 SELECT * FROM TABLE WHERE COLUMN_NAME = @Parameter1)。我想弄清楚的是一种防止此代码不安全的方法。我真的需要这个功能。由于应用程序的目标受众,过去它一直很好,但我不能使用这个特定的代码,因为它会面向客户并且更不开放给公众使用。:/关于我如何实现这一目标的任何建议?
public static void Export(string CrossoverStatement = "SELECT * FROM TABLE")
{
// @@Parameters
//
// CrossoverStatement string :
// This is the string representation of the procedure executed to obtain the desired crossover query results.
//Create our database connection as well as the excel reference and workbook/worksheet we are using to export the data
string ODBCConnection = "SERVER INFO";
Application xls = new Application();
xls.SheetsInNewWorkbook = 1;
// Create our new excel application and add our workbooks/worksheets
Workbook Workbook = xls.Workbooks.Add();
Worksheet CrossoverPartsWorksheet = xls.Worksheets[1];
// Hide our excel object if it's visible.
xls.Visible = false;
// Turn off screen updating so our export will process more quickly.
xls.ScreenUpdating = false;
CrossoverPartsWorksheet.Name = "Crossover";
if (CrossoverStatement != string.Empty)
{
CrossoverPartsWorksheet.Select();
var xlsheet = CrossoverPartsWorksheet.ListObjects.AddEx(SourceType: XlListObjectSourceType.xlSrcExternal,
Source: ODBCConnection,
Destination: xls.Range["$A$1"]).QueryTable;
xlsheet.CommandText = CrossoverStatement;
xlsheet.RowNumbers = false;
xlsheet.FillAdjacentFormulas = false;
xlsheet.PreserveColumnInfo = true;
xlsheet.PreserveFormatting = true;
xlsheet.RefreshOnFileOpen = false;
xlsheet.BackgroundQuery = false;
xlsheet.SavePassword = false;
xlsheet.AdjustColumnWidth = true;
xlsheet.RefreshPeriod = 0;
xlsheet.RefreshStyle = XlCellInsertionMode.xlInsertEntireRows;
xlsheet.Refresh(false);
xlsheet.ListObject.ShowAutoFilter = false;
xlsheet.ListObject.TableStyle = "TableStyleMedium16";
// Unlink our table from the server and convert to a range.
xlsheet.ListObject.Unlink();
// Freeze our column headers.
xls.Application.Rows["2:2"].Select();
xls.ActiveWindow.FreezePanes = true;
xls.ActiveWindow.DisplayGridlines = false;
// Autofit our rows and columns.
xls.Application.Cells.EntireColumn.AutoFit();
xls.Application.Cells.EntireRow.AutoFit();
// Select the first cell in the worksheet.
xls.Application.Range["$A$2"].Select();
// Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages.
xls.DisplayAlerts = false;
}
// Make our excel application visible
xls.Visible = true;
// Release our resources.
Marshal.ReleaseComObject(Workbook);
Marshal.ReleaseComObject(CrossoverPartsWorksheet);
Marshal.ReleaseComObject(xls);
}