本文整理汇总了C#中Microsoft.Office.Interop.Excel.Application.get_Range方法的典型用法代码示例。如果您正苦于以下问题:C# Application.get_Range方法的具体用法?C# Application.get_Range怎么用?C# Application.get_Range使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Office.Interop.Excel.Application
的用法示例。
在下文中一共展示了Application.get_Range方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DisplayInExcel
static void DisplayInExcel(this IEnumerable<Account> accounts,
Action<Account, Excel.Range> DisplayFunc)
{
var x1 = new Excel.Application();
//see the Note below
x1.Workbooks.Add();
x1.Visible = true;
x1.get_Range("A1").Value2 = "ID";
x1.get_Range("B1").Value2 = "Balance";
x1.get_Range("C1").Value2 = "Account Holder";
x1.get_Range("A2").Select();
foreach (var ac in accounts)
{
DisplayFunc(ac, x1.ActiveCell);
x1.ActiveCell.get_Offset(1, 0).Select();
}
((Excel.Range)x1.Columns[1]).AutoFit();
((Excel.Range)x1.Columns[2]).AutoFit();
((Excel.Range)x1.Columns[3]).AutoFit();
x1.get_Range("A1:C4").Copy();
}
示例2: ConvertDLMtoExcel
public void ConvertDLMtoExcel(string filePath, string OutputFile)
{
if (File.Exists(OutputFile)) File.Delete(OutputFile);
string[] DLM_Rows = System.IO.File.ReadAllLines(filePath);
char[] DLM = textBox4.Text.ToCharArray();
int num_rows = DLM_Rows.Length, num_cols = DLM_Rows[0].Split(DLM).Length;
object[,] rawData = new object[num_rows, num_cols];
for (int r = 0; r < num_rows; r++)
{
string[] line_r = DLM_Rows[r].Split(DLM);
for (int c = 0; c < num_cols; c++) rawData[r, c] = line_r[c];
}
if (textBox2.Text.ToLower() == "xlsx" || textBox2.Text.ToLower() == "xls" )
{
for (int r = 0; r < num_rows; r++)
{
for (int c = 0; c < num_cols; c++) rawData[r, c] = "'" + rawData[r, c];
}
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Add(true);
string excelRange = string.Format("A1:{0}{1}", LastCoulmLetter(num_cols), num_rows);
excel.get_Range(excelRange, Type.Missing).Value2 = rawData;
if (textBox6.Text == "") { }
else excel.Worksheets.get_Item(1).Name = textBox6.Text;
if (textBox2.Text.ToLower() == "xlsx") { workBook.SaveAs(OutputFile); }
else {workBook.SaveAs(OutputFile, Excel.XlFileFormat.xlWorkbookNormal); }
workBook.Close();
}
else if (textBox2.Text.ToLower().Contains("xls")) { }
else
{
using (var wtr = new StreamWriter(OutputFile))
{
for (int r = 0; r < num_rows; r++)
{
bool firstLine = true;
for (int c = 0; c < num_cols; c++)
{
if (!firstLine) wtr.Write(textBox1.Text);
else firstLine = false;
wtr.Write(String.Format("{0}", rawData[r, c].ToString().Replace("\"", "\"\"").Replace(",", "")));
}
wtr.WriteLine();
}
}
}
}
示例3: CSharp2008
static void CSharp2008()
{
var excelApp = new Excel.Application();
excelApp.Workbooks.Add(Type.Missing);
excelApp.Visible = true;
Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing);
targetRange.set_Value(Type.Missing, "Name");
// Or
//targetRange.Value2 = "Name";
}
开发者ID:terryjintry,项目名称:OLSource1,代码行数:11,代码来源:how-to--use-indexed-properties-in-com-interop-programming--csharp-programming-guide-_5.cs
示例4: GenerateChart
static void GenerateChart(bool copyToWord = false)
{
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add();
excel.Range["A1"].Value2 = "Process Name";
excel.Range["B1"].Value2 = "Memory Usage";
var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet64)
.Take(10);
int i = 2;
foreach (var p in processes)
{
excel.Range["A" + i].Value2 = p.ProcessName;
excel.Range["B" + i].Value2 = p.WorkingSet64;
i++;
}
Excel.Range range = excel.get_Range("A1");
Excel.Chart chart = (Excel.Chart)excel.ActiveWorkbook.Charts.Add(
After: excel.ActiveSheet);
chart.ChartWizard(Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName);
chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);
if (copyToWord)
{
var word = new Word.Application();
word.Visible = true;
word.Documents.Add();
word.Selection.Paste();
}
}
示例5: DisplayInExcel
public static void DisplayInExcel(IEnumerable<Account> accounts,
Action<Account, Excel.Range> DisplayFunc)
{
var xl = new Excel.Application();
xl.Workbooks.Add();
xl.Visible = true;
xl.Cells[1, 1] = "ID";
xl.Cells[1, 2] = " Balance";
xl.Cells[2, 1].Select();
foreach (var ac in accounts)
{
DisplayFunc(ac, xl.ActiveCell);
xl.ActiveCell.get_Offset(1, 0).Select();
}
xl.get_Range("A1:B3").Copy();
xl.Columns[1].AutoFit();
xl.Columns[2].AutoFit();
}
示例6: button5_Click
private void button5_Click(object sender, EventArgs e)
{
saveDump();
StreamReader reader = new StreamReader(pathToReportHtml, Encoding.GetEncoding("windows-1251"));
string body = reader.ReadToEnd();
reader.Close();
reader.Dispose();
int num = alert_emty_cells();
if (num!=0)
{
MessageBox.Show("Не заполнено ячеек: " + num + " !!!");
}
if (workbookPath == "")
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
workbookPath = openFileDialog1.FileName;
}
Thread t5 = new Thread(delegate ()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
//Тестирование сохранения в файл Excel
//--Формирование итогового отчёта--\\
Excel.Range dateFind = null;
Excel.Range timeFind = null;
Excel.Workbook excelWorkbook = null;
var ReportApp = new Excel.Application();
ReportApp.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
if (workbookPath != "")
{
try
{
// excelWorkbook = ReportApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
excelWorkbook = ReportApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("Сверка");
Excel.Worksheet excelReportSheet = (Excel.Worksheet)excelSheets.get_Item("Отчет");
//алгоритм поиска необходимой строки
excelWorksheet.Activate();
int i = 1;
while (dateFind == null && i != 1000)
{
Excel.Range Date = ReportApp.get_Range("A" + i.ToString(), "B" + (i * 24).ToString());
dateFind = Date.Find(dayBox.Text + "." + monthBox.Text + "." + yearBox.Text);
if (dateFind != null) //если найдена сегодняшняя дата, то ищем текущий час идущий после значения даты.
{
Excel.Range Time = ReportApp.get_Range("A" + i.ToString(), "B" + (i * 480).ToString());
timeFind = Time.Find(timeBox.Text + ":00", dateFind);//DateTime.Now.ToString("HH") вместо текстбокса
}
i++;
//return timeFind.Row
}
//алгоритм поиска необходимой строки
if (dateFind != null)//если искомая строка найдена
{
//--блок заполнения листа со сверкой
excelWorksheet.Range["C:BH"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BO:BU"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BX:CA"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BI:BN"].NumberFormat = "#,##0";
excelWorksheet.Range["BV:BW"].NumberFormat = "#,##0";
for(int k = 0; k < cells.Length; k++)
{
cells[k].Value = cells[k].Value.ToString().Replace(" ", "");
}
excelWorksheet.Cells[timeFind.Row, "C"] = DataProcessing.parseDoub(cells[0].Value.ToString().Replace(",","."));//Позиция отчёта Comepay
excelWorksheet.Cells[timeFind.Row, "E"] = DataProcessing.parseDoub(cells[1].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "I"] = DataProcessing.parseDoub(cells[2].Value.ToString().Replace(",", ".")); //Позиция отчёта cyberplat
if (DataProcessing.parseDoub(timeBox.Text) != 0)
{
excelWorksheet.Cells[timeFind.Row + 1, "K"] = DataProcessing.parseDoub(cells[3].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row + 1, "M"] = DataProcessing.parseDoub(cells[4].Value.ToString().Replace(",", "."));
}
excelWorksheet.Cells[timeFind.Row, "Q"] = DataProcessing.parseDoub(cells[5].Value.ToString().Replace(",", ".")); //Позиция отчёта OSMP
excelWorksheet.Cells[timeFind.Row, "S"] = DataProcessing.parseDoub(cells[6].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "W"] = DataProcessing.parseDoub(cells[7].Value.ToString().Replace(",", "."));//Позиция отчёта Короны
excelWorksheet.Cells[timeFind.Row, "Y"] = DataProcessing.parseDoub(cells[8].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AC"] = DataProcessing.parseDoub(cells[9].Value.ToString().Replace(",", ".")); //Позиция отчёта яндекса
excelWorksheet.Cells[timeFind.Row, "AE"] = DataProcessing.parseDoub(cells[10].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AF"] = DataProcessing.parseDoub(cells[11].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AH"] = DataProcessing.parseDoub(cells[12].Value.ToString().Replace(",", "."));
//.........这里部分代码省略.........
示例7: ExportToExcel2008
static void ExportToExcel2008(List<Car> carsInStock)
{
Excel.Application excelApp = new Excel.Application();
// Must mark missing params!
excelApp.Workbooks.Add(Type.Missing);
// Must cast Object as _Worksheet!
Excel._Worksheet workSheet = (Excel._Worksheet)excelApp.ActiveSheet;
// Must cast each Object as Range object then call
// call low level Value2 property!
((Excel.Range)excelApp.Cells[1, "A"]).Value2 = "Make";
((Excel.Range)excelApp.Cells[1, "B"]).Value2 = "Color";
((Excel.Range)excelApp.Cells[1, "C"]).Value2 = "Pet Name";
int row = 1;
foreach (Car c in carsInStock)
{
row++;
// Must cast each Object as Range and call low level Value2 prop!
((Excel.Range)workSheet.Cells[row, "A"]).Value2 = c.Make;
((Excel.Range)workSheet.Cells[row, "B"]).Value2 = c.Color;
((Excel.Range)workSheet.Cells[row, "C"]).Value2 = c.PetName;
}
// Must call get_Range method and then specify all missing args!.
excelApp.get_Range("A1", Type.Missing).AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
// Must specify all missing optional args!
workSheet.SaveAs(string.Format(@"{0}\Inventory.xlsx", Environment.CurrentDirectory),
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
excelApp.Quit();
MessageBox.Show("The Inventory.xslx file has been saved to your app folder", "Export complete!");
}
示例8: SaveExcel
//重新另存為Excel的xls
private bool SaveExcel(string path)
{
bool result = false;
Excel.Application AppExcel = new Excel.Application();
try
{
if (AppExcel == null)
{
throw new Exception("无法创建Excel对象,可能您的机器未安装Excel");
}
Excel.Workbook workBook = AppExcel.Application.Workbooks.Open(path, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];
workSheet.Name = "過膠機生產日報表" + DateTime.Now.ToString("yyyy-MM-dd");
workSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4; //設置頁面A4打印
workSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; //設置橫向打印
workSheet.PageSetup.Zoom = false; //設置頁面縮放比例 Zoom必須設為False FitToPagesWide才有效
workSheet.PageSetup.FitToPagesWide = 1;//設置葉寬為一頁
workSheet.PageSetup.CenterHorizontally = true;//頁面水平居中
workSheet.PageSetup.TopMargin = AppExcel.InchesToPoints(0.275590551181102);
workSheet.PageSetup.BottomMargin = AppExcel.InchesToPoints(0.196850393700787);
workSheet.PageSetup.LeftMargin = AppExcel.InchesToPoints(0.196850393700787);
workSheet.PageSetup.RightMargin = AppExcel.InchesToPoints(0.196850393700787);
workSheet.PageSetup.FooterMargin = AppExcel.InchesToPoints(0.31496062992126);
workSheet.PageSetup.HeaderMargin = AppExcel.InchesToPoints(0.31496062992126);
AppExcel.get_Range(AppExcel.Cells[4, 15], AppExcel.Cells[m_dataTabel.Rows.Count + 3, 17]).NumberFormat = "0.00";
AppExcel.get_Range(AppExcel.Cells[4, 27], AppExcel.Cells[m_dataTabel.Rows.Count + 3, 27]).NumberFormat = "0.00";
AppExcel.Visible = false;
workBook.SaveCopyAs(m_SaveExcelPath);
}
catch (Exception ex)
{
throw ex;
}
finally
{
//if (File.Exists(m_TempPath)) File.Delete(m_TempPath); //刪除開始生成的臨時xls
AppExcel.Quit();
IntPtr t = new IntPtr(AppExcel.Hwnd); //杀死进程的好方法
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
System.GC.Collect();
}
return result;
}
示例9: finalReportButton_Click
/// <summary>
/// Этот метод находится в разработке.
/// </summary>m>
//--Кнопка обработки файла Мониторинг Платежных Систем--\\
private void finalReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
string workbookPath = openFileDialog1.FileName;
Thread t5 = new Thread(delegate ()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
//Тестирование сохранения в файл Excel
//--Формирование итогового отчёта--\\
Excel.Range dateFind = null;
Excel.Range timeFind = null;
Excel.Workbook excelWorkbook = null;
var excelApp = new Excel.Application();
if (workbookPath != "")
{
try
{
excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("Сверка");
Excel.Worksheet excelReportSheet = (Excel.Worksheet)excelSheets.get_Item("Отчет");
//алгоритм поиска необходимой строки
int i = 1;
while (dateFind == null && i != 1000)
{
Excel.Range Date = excelApp.get_Range("A" + i.ToString(), "B" + (i * 24).ToString());
dateFind = Date.Find(dayBox.Text + "." + monthBox.Text + "." + yearBox.Text);
if (dateFind != null) //если найдена сегодняшняя дата, то ищем текущий час идущий после значения даты.
{
Excel.Range Time = excelApp.get_Range("A" + i.ToString(), "B" + (i * 480).ToString());
timeFind = Time.Find(DateTime.Now.ToString("HH") + ":00", dateFind);
}
textBox3.AppendText(i.ToString() + "\n");
i++;
//return timeFind.Row
}
//алгоритм поиска необходимой строки
if (dateFind != null)//если искомая строка найдена
{
//--блок заполнения листа со сверкой
excelWorksheet.Cells[timeFind.Row, "AD"] = tabReport_YandexReport.Text; //Позиция отчёта яндекса
excelWorksheet.Cells[timeFind.Row, "AA"] = tabReport_YandexEkassir.Text;
excelWorksheet.Cells[timeFind.Row, "AB"] = tabReport_YandexHourEkassir.Text;
excelWorksheet.Cells[timeFind.Row, "K"] = tabReport_textCyberReport.Text; //Позиция отчёта cyberplat
excelWorksheet.Cells[timeFind.Row, "I"] = tabReport_CyberEkassir.Text;
excelWorksheet.Cells[timeFind.Row, "C"] = tabReport_ComepayEkassir.Text;//Позиция отчёта Comepay
excelWorksheet.Cells[timeFind.Row, "E"] = tabReport_ComepayReport.Text;
excelWorksheet.Cells[timeFind.Row, "O"] = tabReport_OSMPEkassir.Text;//Позиция отчёта OSMP
excelWorksheet.Cells[timeFind.Row, "Q"] = tabReport_OSMPReport.Text;
excelWorksheet.Cells[timeFind.Row, "AI"] = tabReport_RapidaReport.Text;//Позиция отчёта Рапиды
excelWorksheet.Cells[timeFind.Row, "AG"] = tabReport_RapidaEkassir.Text;
excelWorksheet.Cells[timeFind.Row, "U"] = tabReport_CrownEkassir.Text;//Позиция отчёта Короны
excelWorksheet.Cells[timeFind.Row, "W"] = tabReport_CrownReport.Text;
excelWorksheet.Cells[timeFind.Row, "AN"] = tabReport_SvzBankReport.Text;//Позиция отчёта Связного банка
excelWorksheet.Cells[timeFind.Row, "CB"] = dataGridView1.Rows[0].Cells[0].Value;
//--конец блока заполнения листа со сверкой
//--блок заполнения листа с отчётом
excelReportSheet.Range["A6", "F6"].Value = excelWorksheet.Range["C" + timeFind.Row.ToString(), "H" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A10", "F10"].Value = excelWorksheet.Range["I" + timeFind.Row.ToString(), "N" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A14", "F14"].Value = excelWorksheet.Range["O" + timeFind.Row.ToString(), "T" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A18", "F18"].Value = excelWorksheet.Range["U" + timeFind.Row.ToString(), "Z" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A22", "F22"].Value = excelWorksheet.Range["AA" + timeFind.Row.ToString(), "AF" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A26", "F26"].Value = excelWorksheet.Range["AG" + timeFind.Row.ToString(), "AL" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A34", "B34"].Value = excelWorksheet.Range["AM" + timeFind.Row.ToString(), "AN" + timeFind.Row.ToString()].Value;
excelReportSheet.Range["A2"].Value = DateTime.Now.ToString("dd.MM.yyyy");
excelReportSheet.Range["E2"].Value = DateTime.Now.ToString("HH" + ":00");
//--конец блока заполнения листа с отчётом
excelReportSheet.Range["A1", "H34"].Copy();//занесение отчёта в буфер обмена
//MAILER
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = Clipboard.GetText(TextDataFormat.Html);
//Subject line
oMsg.Subject = "Тема";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
//.........这里部分代码省略.........
示例10: CovertExcelToDLM
public void CovertExcelToDLM(string excelFilePath, string OutputFile)
{
if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
if (File.Exists(OutputFile)) File.Delete(OutputFile);
var dt = new System.Data.DataTable();
System.Data.OleDb.OleDbConnection cnn = excel_func.Conn(BoxInExt.Text , excelFilePath, true);
DataSet set = new DataSet();
if (BoxInTabName.Text.All(char.IsDigit))
{
int worksheetNumber = Convert.ToInt32(BoxInTabName.Text);
try
{
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable.Rows.Count < worksheetNumber) { throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet"); }
string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheet);
OleDbDataAdapter da = new OleDbDataAdapter(sql, cnn);
da.Fill(set);
}
catch (Exception e) { throw e; }
finally{ cnn.Close(); }
}
else
{
string worksheetName = BoxInTabName.Text;
try
{
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sql = String.Format("select * from [{0}]", worksheetName + "$");
var da = new OleDbDataAdapter(sql, cnn);
da.Fill(set);
}
catch (Exception e) { throw e; }
finally { cnn.Close(); }
}
int num_rows = set.Tables[0].Rows.Count, num_cols = set.Tables[0].Columns.Count;
object[,] rawData = new object[num_rows + 1, num_cols];
for (int col = 0; col < num_cols; col++) rawData[0, col] = set.Tables[0].Columns[col].ColumnName; // column names
for (int col = 0; col < num_cols; col++) //rest data
{
for (int row = 0; row < num_rows; row++)
{
rawData[row + 1, col] = set.Tables[0].Rows[row].ItemArray[col].ToString();
if (rawData[row + 1, col].ToString().All(char.IsDigit) && BoxOutExt.Text.ToLower().Contains("csv"))
{ rawData[row + 1, col] = "'" + rawData[row + 1, col]; }
}
}
if (BoxOutExt.Text.ToLower() == "xlsx" || BoxOutExt.Text.ToLower() == "xls")
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Add(true);
string excelRange = string.Format("A1:{0}{1}", excel_func.LastCoulmLetter(num_cols), num_rows + 1);
excel.get_Range(excelRange, Type.Missing).Value2 = rawData;
if (BoxOutExt.Text.ToLower() == "xlsx") { workBook.SaveAs(OutputFile); }
else { workBook.SaveAs(OutputFile, Excel.XlFileFormat.xlWorkbookNormal); }
workBook.Close();
excel.Quit();
excel = null;
}
else if (BoxOutExt.Text.ToLower().Contains("xls")) { }
else
{
using (var wtr = new StreamWriter(OutputFile))
{
for (int r = 0; r < num_rows; r++)
{
bool firstLine = true;
for (int c = 0; c < num_cols; c++)
{
if (!firstLine) wtr.Write(BoxOutDlm.Text);
else firstLine = false;
wtr.Write(String.Format("{0}", rawData[r, c].ToString().Replace("\"", "\"\"").Replace(BoxOutDlm.Text, "")));
}
wtr.WriteLine();
}
}
}
}
示例11: ConvertDLMtoExcel
public void ConvertDLMtoExcel(string filePath, string filename , string OutputFile)
{
if (File.Exists(OutputFile)) File.Delete(OutputFile);
int num_rows = 0, num_cols = 0, curr_row = 0;
string line;
char[] DLM = BoxInDlm.Text.ToCharArray();
int[] FileDim = null;
try {
if (JustReplaceDelim.Checked)
{
FileDim = text_func.CalcFileDimentions(filePath, BoxInDlm.Text , false);
}
else
{
FileDim = text_func.CalcFileDimentions(filePath, BoxInDlm.Text);
}
}catch(Exception ex)
{
text_func.ErrorToLog(LogFile, ex.ToString());
}
num_rows = FileDim[0];
num_cols = FileDim[1];
object[,] rawData = new object[num_rows, num_cols ];
string TempDelim;
System.IO.StreamReader file = new System.IO.StreamReader(filePath, Encoding.Default);
while ((line = file.ReadLine()) != null)
{
string[] line_r;
if (JustReplaceDelim.Checked)
{
if (BoxOutDlm.Text == ",") { TempDelim = "."; }
else
{
TempDelim = "_";
}
line_r = new string[] { line.Replace( BoxOutDlm.Text , TempDelim).Replace(BoxInDlm.Text, BoxOutDlm.Text) };
}
else
{
line_r = line.Split(DLM);
if (num_cols < line_r.Length)
{
line_r = text_func.Split(line, BoxInDlm.Text.ToString(), "\"", true);
};
}
for (int c = 0; c < line_r.Length; c++)
{ rawData[curr_row, c] = line_r[c]; }
for (int c = line_r.Length; c < num_cols; c++)
{ rawData[curr_row, c] = ""; }
line_r = null;
curr_row++;
}
file.Close();
var lst = new List<string>() { "xlsx", "xlsb", "xls", "xlsm" };
if (lst.Contains(BoxOutExt.Text, StringComparer.OrdinalIgnoreCase))
{
for (int r = 0; r < num_rows; r++)
{
for (int c = 0; c < num_cols; c++)
{
if (rawData[r, c].ToString().All(char.IsDigit) && rawData[r, c].ToString().Length > 0) rawData[r, c] = "'" + rawData[r, c];
}
}
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Add(true);
workBook.CheckCompatibility = false;
string excelRange = string.Format("A1:{0}{1}", excel_func.LastCoulmLetter(num_cols), num_rows);
try
{
excel.get_Range(excelRange, Type.Missing).Value2 = rawData;
}
catch (Exception ex)
{
string tempfile = filename;
string Tempr = "";
string Tempc = "";
string TempVal = "" ;
var sh = (_Worksheet)workBook.ActiveSheet;
for (int r = 0; r < num_rows; r++)
{
for (int c = 0; c < num_cols; c++)
{
try
{
Tempr = Convert.ToString(r);
Tempc = Convert.ToString(c);
//.........这里部分代码省略.........
示例12: button5_Click
private void button5_Click(object sender, EventArgs e)
{
int num = alert_emty_cells();
if (num!=0)
{
MessageBox.Show("Не заполнено ячеек: " + num + " !!!");
}
if (workbookPath == "")
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
workbookPath = openFileDialog1.FileName;
}
Thread t5 = new Thread(delegate ()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
//Тестирование сохранения в файл Excel
//--Формирование итогового отчёта--\\
Excel.Range dateFind = null;
Excel.Range timeFind = null;
Excel.Workbook excelWorkbook = null;
var ReportApp = new Excel.Application();
ReportApp.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
if (workbookPath != "")
{
try
{
// excelWorkbook = ReportApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
excelWorkbook = ReportApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("Сверка");
Excel.Worksheet excelReportSheet = (Excel.Worksheet)excelSheets.get_Item("Отчет");
//алгоритм поиска необходимой строки
excelWorksheet.Activate();
int i = 1;
while (dateFind == null && i != 1000)
{
Excel.Range Date = ReportApp.get_Range("A" + i.ToString(), "B" + (i * 24).ToString());
dateFind = Date.Find(dayBox.Text + "." + monthBox.Text + "." + yearBox.Text);
if (dateFind != null) //если найдена сегодняшняя дата, то ищем текущий час идущий после значения даты.
{
Excel.Range Time = ReportApp.get_Range("A" + i.ToString(), "B" + (i * 480).ToString());
timeFind = Time.Find(textBox1.Text + ":00", dateFind);//DateTime.Now.ToString("HH") вместо текстбокса
}
i++;
//return timeFind.Row
}
//алгоритм поиска необходимой строки
if (dateFind != null)//если искомая строка найдена
{
//--блок заполнения листа со сверкой
// excelWorksheet.Columns("C").NumberFormat = "#,##0";
excelWorksheet.Range["C:BH"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BO:BU"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BX:CA"].NumberFormat = "#,##0.00";
excelWorksheet.Range["BI:BN"].NumberFormat = "#,##0";
excelWorksheet.Range["BV:BW"].NumberFormat = "#,##0";
//string[] index = new string[35] { "C","E","I","K","M","Q","S","W","Y","AC","AE","AF","AH","AK","AM","AO","AS","AU","AW","AY",
// "BA","BC","BE","BG","BI","BK","BO","BQ","BV","BX","BZ","G6","G14","G22","G26"};
for(int k = 0; k < cells.Length; k++)
{
cells[k].Value = cells[k].Value.ToString().Replace(" ", "");
// excelWorksheet.Cells[timeFind.Row, index[k]] = Double.Parse(cells[k].Value.ToString().Replace(",", "."));
}
excelWorksheet.Cells[timeFind.Row, "C"] = DataProcessing.parseDoub(cells[0].Value.ToString().Replace(",","."));//Позиция отчёта Comepay
excelWorksheet.Cells[timeFind.Row, "E"] = DataProcessing.parseDoub(cells[1].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "I"] = DataProcessing.parseDoub(cells[2].Value.ToString().Replace(",", ".")); //Позиция отчёта cyberplat
if (DataProcessing.parseDoub(textBox1.Text) != 0)
{
excelWorksheet.Cells[timeFind.Row + 1, "K"] = DataProcessing.parseDoub(cells[3].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row + 1, "M"] = DataProcessing.parseDoub(cells[4].Value.ToString().Replace(",", "."));
}
excelWorksheet.Cells[timeFind.Row, "Q"] = DataProcessing.parseDoub(cells[5].Value.ToString().Replace(",", ".")); //Позиция отчёта OSMP
excelWorksheet.Cells[timeFind.Row, "S"] = DataProcessing.parseDoub(cells[6].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "W"] = DataProcessing.parseDoub(cells[7].Value.ToString().Replace(",", "."));//Позиция отчёта Короны
excelWorksheet.Cells[timeFind.Row, "Y"] = DataProcessing.parseDoub(cells[8].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AC"] = DataProcessing.parseDoub(cells[9].Value.ToString().Replace(",", ".")); //Позиция отчёта яндекса
excelWorksheet.Cells[timeFind.Row, "AE"] = DataProcessing.parseDoub(cells[10].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AF"] = DataProcessing.parseDoub(cells[11].Value.ToString().Replace(",", "."));
excelWorksheet.Cells[timeFind.Row, "AH"] = DataProcessing.parseDoub(cells[12].Value.ToString().Replace(",", "."));
//.........这里部分代码省略.........
示例13: button1_Click
private void button1_Click(object sender, EventArgs e)
{
//load worksheet
Excel.Application objexcel = new Excel.Application();
Excel.Workbook owb = objexcel.Workbooks.Open(textBox1.Text,
Type.Missing,
false,
Type.Missing,
Type.Missing,
Type.Missing,
true,
Type.Missing,
Type.Missing,
true,
false,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
Excel.Worksheet ows = (Excel.Worksheet)owb.Worksheets[1];
objexcel.Visible = false;
int Rub = 1000; //row upper bound
try
{
for (int j = 9; j < Rub; j++)
{
object Val = objexcel.get_Range("A" + j, "A" + j).Value;
if (Val == null || Val.ToString() == "")
Rub = j;
}
}
catch { }
SqlTransaction transaction = null;
int i = 0;
try
{
transaction = TableHelper.BeginTransaction(eSRLogTableAdapter);
for (i = 9; i < Rub; i++)
{
object projectnum = null;
object business = null;
object productline = null;
object projdesc = null;
object partnumber = null;
object customer = null;
object requestedby = null;
object receiveddate = null;
object priority = null;
object engassigned = null;
object tocust = null;
object tocost = null;
object notes = null;
object eco = null;
object status = null;
object completiondate = null;
try
{
projectnum = objexcel.get_Range("A" + i, "A" + i).Value;
if (projectnum == null)
projectnum = "";
business = objexcel.get_Range("B" + i, "B" + i).Value;
if (business == null)
business = "";
productline = objexcel.get_Range("C" + i, "C" + i).Value;
if (productline == null)
productline = "";
projdesc = objexcel.get_Range("D" + i, "D" + i).Value;
//.........这里部分代码省略.........
示例14: ExportToExcel
/**/
/// <summary>
/// ��DataGridView�е����ݵ�����Excel�У���������ʾ����(����ģ��)
/// ֻ����һ��ĵ���Excel
/// </summary>
/// <param name="caption">Ҫ��ʾ��ҳͷ</param>
/// <param name="date">��ӡ����</param>
/// <param name="dgv">Ҫ���е�����DataGridView</param>
public void ExportToExcel(string caption, string date, DataGridView dgv)
{
//DataGridView�ɼ�����
int visiblecolumncount = 0;
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (dgv.Columns[i].Visible == true && (dgv.Columns[i] is DataGridViewTextBoxColumn))
{
visiblecolumncount++;
}
}
try
{
//��ǰ�����е�����
int currentcolumnindex = 1;
//��ǰ�����е�����
Microsoft.Office.Interop.Excel.ApplicationClass Mylxls = new Microsoft.Office.Interop.Excel.ApplicationClass();
Mylxls.Application.Workbooks.Add(true);
//Mylxls.Cells.Font.Size = 10.5; //����Ĭ�������С
//���ñ�ͷ
Mylxls.Caption = caption;
//��ʾ��ͷ
Mylxls.Cells[1, 1] = caption;
//��ʾʱ��
Mylxls.Cells[2, 1] = date;
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (dgv.Columns[i].Visible == true && (dgv.Columns[i] is DataGridViewTextBoxColumn)) //�����ʾ
{
Mylxls.Cells[3, currentcolumnindex] = dgv.Columns[i].HeaderText;
Mylxls.get_Range(Mylxls.Cells[3, currentcolumnindex], Mylxls.Cells[3, currentcolumnindex]).Cells.Borders.LineStyle = 1; //���ñ߿�
Mylxls.get_Range(Mylxls.Cells[3, currentcolumnindex], Mylxls.Cells[3, currentcolumnindex]).ColumnWidth = dgv.Columns[i].Width / 8;
//Mylxls.get_Range(Mylxls.Cells[3, currentcolumnindex], Mylxls.Cells[3, currentcolumnindex]).Font.Bold = true; //����
//Mylxls.get_Range(Mylxls.Cells[3, currentcolumnindex], Mylxls.Cells[3, currentcolumnindex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; //������ʾ
currentcolumnindex++;
}
}
Mylxls.get_Range(Mylxls.Cells[1, 1], Mylxls.Cells[1, visiblecolumncount]).MergeCells = true; //�ϲ���Ԫ��
Mylxls.get_Range(Mylxls.Cells[1, 1], Mylxls.Cells[1, 1]).RowHeight = 30; //�и�
//Mylxls.get_Range(Mylxls.Cells[1, 1], Mylxls.Cells[1, 1]).Font.Name = "����";
//Mylxls.get_Range(Mylxls.Cells[1, 1], Mylxls.Cells[1, 1]).Font.Size = 14; //�����С
Mylxls.get_Range(Mylxls.Cells[1, 1], Mylxls.Cells[1, visiblecolumncount]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //������ʾ
Mylxls.get_Range(Mylxls.Cells[2, 1], Mylxls.Cells[2, 2]).MergeCells = true; //�ϲ�
Mylxls.get_Range(Mylxls.Cells[2, 1], Mylxls.Cells[2, 2]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //�����ʾ
//Mylxls.get_Range(Mylxls.Cells[1, 2], Mylxls.Cells[1, 2]).ColumnWidth = 12; //��
object[,] dataArray = new object[dgv.Rows.Count, visiblecolumncount];
//��ǰ�����е�����
//int currentcolumnindex = 1;
//��ǰ�����е�����
for (int i = 0; i < dgv.Rows.Count; i++) //ѭ���������
{
currentcolumnindex = 1;
for (int j = 0; j < dgv.Columns.Count; j++)
{
if (dgv.Columns[j].Visible == true && (dgv.Columns[j] is DataGridViewTextBoxColumn))
{
if (dgv[j, i].Value != null) //�����Ԫ�����ݲ�Ϊ��
{
dataArray[i, currentcolumnindex - 1] = dgv[j, i].Value.ToString();
}
currentcolumnindex++;
}
}
}
Mylxls.get_Range(Mylxls.Cells[4, 1], Mylxls.Cells[dgv.Rows.Count + 3, visiblecolumncount]).Value2 = dataArray; //���ñ߿�
Mylxls.get_Range(Mylxls.Cells[4, 1], Mylxls.Cells[dgv.Rows.Count + 3, visiblecolumncount]).Cells.Borders.LineStyle = 1; //���ñ߿�
Mylxls.Visible = true;
}
catch
{
MessageBox.Show("��Ϣ����ʧ�ܣ���ȷ����Ļ�����װ��Microsoft Office Excel 2003��", "����", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}
/**/
/// <summary>
/// ��DataGridView�е����ݵ�����Excel�У���������ʾ����(����ģ��)
/// �����ڵ����Ѷ����ģ���Excel��������Ҫ�硰Ѯ����������±������
/// ��ע�⣺ģ��Ӧ����Ӧ�����PrintTemplateĿ¼��
/// </summary>
/// <param name="ModelName">ģ�������</param>
/// <param name="Date">��ӡ����</param>
/// <param name="dgv">Ҫ���е�����DataGridView</param>
public void ExportToExcelByModel(string ModelName, string Date, DataGridView dgv)
//.........这里部分代码省略.........
示例15: DataGridviewShowToExcel
public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)
{
if (dgv.Rows.Count == 0)
{
MessageBox.Show("当前没有数据,导出失败!");
return false;
}
//建立Excel对象
//int columnCount = dgv.Columns.Count;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
Microsoft.Office.Interop.Excel._Workbook workBook = excel.Workbooks.Add(true);
//新建工作表
Microsoft.Office.Interop.Excel._Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel._Worksheet;
worksheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait;//横向打印
worksheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA3;
worksheet.PageSetup.CenterHorizontally = true;//水平垂直
//worksheet.PageSetup.CenterVertically = true;//
Microsoft.Office.Interop.Excel.Range titleRange = worksheet.get_Range(
worksheet.Cells[1, 1], worksheet.Cells[1, 5]); //选取单元格
titleRange.Merge(true);//合并单元格
titleRange.Value2 = "已使用标识卡统计查询表";//设置单元格内容
titleRange.Font.Name = "黑体";//设置字体
titleRange.Font.Size = 15;//设置字体大小
titleRange.Font.Bold = true;//字体加粗
titleRange.HorizontalAlignment = XlHAlign.xlHAlignCenter;//水平居中
titleRange.VerticalAlignment = XlVAlign.xlVAlignCenter;//垂直居中
double top = 0;
double left = 0;
worksheet.PageSetup.TopMargin = excel.InchesToPoints(top / 1);
worksheet.PageSetup.LeftMargin = excel.InchesToPoints(left / 0);
Microsoft.Office.Interop.Excel.Range titleRange2 = worksheet.get_Range(
worksheet.Cells[2, 1], worksheet.Cells[2, 5]); //选取单元格
titleRange2.Merge(true);//合并单元格
titleRange2.Value2 = dtpBegin.Text+"至"+dtpEnd.Text+" "+"统计人:";//设置单元格内容
//titleRange.Font.Name = "黑体";//设置字体
titleRange2.Font.Size = 10;//设置字体大小
titleRange2.Font.Bold = true;//字体加粗
titleRange2.HorizontalAlignment = XlHAlign.xlHAlignLeft;//水平居中
titleRange2.VerticalAlignment = XlVAlign.xlVAlignCenter;//垂直居中
//设置单元格宽度和高度
excel.get_Range("A1", Missing.Value).ColumnWidth = 15;
excel.get_Range("B1", Missing.Value).ColumnWidth = 15;
excel.get_Range("C1", Missing.Value).ColumnWidth = 15;
excel.get_Range("D1", Missing.Value).ColumnWidth = 15;
excel.get_Range("E1", Missing.Value).ColumnWidth = 15;
excel.get_Range("A1", Missing.Value).RowHeight = 30;
excel.get_Range("A2", Missing.Value).RowHeight = 30;
excel.get_Range("A3", Missing.Value).RowHeight = 30;
excel.get_Range("A4", Missing.Value).RowHeight = 30;
excel.get_Range("A5", Missing.Value).RowHeight = 30;
excel.get_Range("A6", Missing.Value).RowHeight = 30;
excel.get_Range("A7", Missing.Value).RowHeight = 30;
//生成字段名称
for (int i = 0; i < dgv.ColumnCount; i++)
{
excel.Cells[3, i + 1] = dgv.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dgv.RowCount - 1; i++)
{
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv[j, i].ValueType == typeof(string))
{
excel.Cells[i + 4, j + 1] = dgv[j, i].Value.ToString();
}
else
{
excel.Cells[i + 4, j + 1] = dgv[j, i].Value.ToString();
}
//设置边框
excel.get_Range(excel.Cells[dgv.Rows.Count + 2, 5], excel.Cells[3, dgv.Rows.Count]).Cells.Borders.LineStyle = 1;
excel.get_Range(excel.Cells[dgv.Rows.Count + 2, 5], excel.Cells[3, dgv.Rows.Count]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 4], excel.Cells[3, dgv.Rows.Count]).Cells.Borders.LineStyle = 1;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 4], excel.Cells[3, dgv.Rows.Count]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 3], excel.Cells[3, dgv.Rows.Count]).Cells.Borders.LineStyle = 1;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 3], excel.Cells[3, dgv.Rows.Count]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 2], excel.Cells[3, dgv.Rows.Count]).Cells.Borders.LineStyle = 1;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 2], excel.Cells[3, dgv.Rows.Count]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 1], excel.Cells[3, dgv.Rows.Count]).Cells.Borders.LineStyle = 1;
excel.get_Range(excel.Cells[dgv.Rows.Count+2, 1], excel.Cells[3, dgv.Rows.Count]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
}
}
return true;
//.........这里部分代码省略.........